How to take accurate print from RDLC report without saving as pdf - rdlc

I arrange the textbox in rdlc in correct width and height for pre printed page printing. As I take in pdf the alignment of all the labels come correct but I want to take the same without the file getting saved as pdf in system.
In short I don't want to take pdf but still want accurate print like pdf without the file getitng downloaded
enter image description here

I found a solution by rendering the report viewer into pdf and directly will be displayed in PDF Print
Warning[] warnings;
string[] streamIds;
string contentType;
string encoding;
string extension;
//Export the RDLC Report to Byte Array.
byte[] bytes = ReportViewer1.LocalReport.Render("PDF", null, out contentType, out encoding, out extension, out streamIds, out warnings);
// Open generated PDF.
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
Refer
https://www.aspsnippets.com/questions/110559/Export-PDF-from-RDLC-Report-and-open-in-Browser-on-Button-Click-using-C-and-VBNet-in-ASPNet/

Related

Generate PDF from gsp page

I am using grails 2.5.2.
I have created a table which shows all the data from database to gsp page and now i need to save that shown data in a pdf format with a button click.What will be the best way to show them into a PDF and save it to my directory. please Help
You can use itext for converting HTML into pdf using the code below:
public void createPdf(HttpServletResponse response, String args, String css, String pdfTitle) {
response.setContentType("application/force-download")
response.setHeader("Content-Disposition", "attachment;filename=${pdfTitle}.pdf")
Document document = new Document()
Rectangle one = new Rectangle(900, 600)
document.setPageSize(one)
PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream())
document.open()
ByteArrayInputStream bis = new ByteArrayInputStream(args.toString().getBytes())
ByteArrayInputStream cis = new ByteArrayInputStream(css.toString().getBytes())
XMLWorkerHelper.getInstance().parseXHtml(writer, document, bis, cis)
document.close()
}
Though answering this question late,take a look at grails export plugin.It will be useful if you want to export your data to excel and pdf( useful only if there is no in pre-defined template to export).
Got idea from itext. Used itext 2.1.7 and posted all the values to pdf from a controller method. Used images as background and paragraph and phrase to show values from database.

PDF generated using PDFBox is magnified when printing / saving via Safari

I generated a pdf using PDFBox which is then sent to the front-end. When I print / save this pdf in Chrome / Firefox, it looks good. However, when I try to do the same using Safari, the pdf is magnified.
Not sure if this is a browser issue or whether it has something to do with Safari not able to read the pdf properly. Any ideas?
This is the pdf generated from Chrome, and this is the one from Safari (I've redacted few details).
This is my code:
PDXObjectImage blankImg = (PDXObjectImage) object;
if(blankImg.getHeight() > 460){
BufferedImage img = ImageIO.read(new ByteArrayInputStream(shippingLabel));
BufferedImage resizedImage = Scalr.resize(img, Scalr.Method.BALANCED, Scalr.Mode.FIT_EXACT, img.getWidth(), img.getHeight());
// Convert images to jpg format
BufferedImage jpegImage = new BufferedImage(resizedImage.getWidth(),resizedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
jpegImage.createGraphics().drawImage(resizedImage, 0, 0, Color.WHITE, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(jpegImage, "jpg", baos);
// Replace empty image in template with the image generated from shipping label byte array
PDXObjectImage carrierLabel = new PDJpeg(doc, new ByteArrayInputStream(baos.toByteArray()));
blankImg.getCOSStream().replaceWithStream(carrierLabel.getCOSStream());
break;
}
PDStream updatedStream = new PDStream(doc);
OutputStream out = updatedStream.createOutputStream();
ContentStreamWriter tokenWriter = new ContentStreamWriter(out);
tokenWriter.writeTokens(tokens);
page.setContents(updatedStream);
// Convert PDDoc to byte[]
ByteArrayOutputStream outUpdated = new ByteArrayOutputStream();
doc.save(outUpdated);
return outUpdated.toByteArray();
This is what I'm doing. I have a pdf with a blank image. I read this image, and replace this with another existing image which is available as byte array, and finally return the updated pdf as a byte array as ResponseEntity from Spring boot server running in the backend.
Thanks.

Internet Explorer file download prompt character encoding

In Internet Explorer running an MVC 4 application, when downloading a file with an Arabic filename, the download prompt displays a filename which appears to be in the wrong character set. Please see the attached image.
If it's possible to alter the display of this filename how do I do it?
If you are using the return File method, try encoding the file name
var fileName = Path.GetFileName(filePath);
if (Request.Browser.Browser == "IE")
{
string attachment = string.Format("attachment; filename=\"{0}\"",
Server.UrlPathEncode(fileName));
Response.AddHeader("Content-Disposition", attachment);
}
return File(filePath, "application/octet-stream", fileName);

Primefaces generate pdf and display on click of button

I have a requirement in which I have to generate a pdf and then on click of button "SHOW PDF", I have to display on another window.
I have been able to generate a pdf using IText and stored in my machine. I get a java.io.File object as my return value from my backend library which needs to be displayed on the screen. Can someone please guide me how to do this?
My xhtml file has the following code snippet:
<h:commandLink action="PdfDisplayRedirect.xhtml" target="_blank">show PDF</h:commandLink>
my PdfDisplayRedirect.xhtml has the following code:
<p:media value="#{pdfGenerationAction.fileName}" width="100%" height="300px">
Your browser can't display pdf, <h:outputLink value="InitialExamination33.pdf">click</h:outputLink> to download pdf instead.
My backing bean has the following code:
private File initialExaminationFile;
private generateFile(){
this.initialExaminationFile = backendService.generateFile();
}
On clicking, I get a new window opened but the pdf file is not displayed.. Instead my screen from where I had invoked the command gets displayed there.
Any help would be really appreciated.
Thanks
Thanks for the response and no response.
I have found a solution myself which I would like to post so that those looking for a solution can use it.
My xhtml file included a commandlink
<p:commandLink actionListener="#{pdfGenerationAction.generatePDF(initialExaminationEMRAction.patientID)}" oncomplete="window.open('PdfDisplayRedirect.xhtml')">broadcast Msg</p:commandLink>
My pdfGenerationAction bean file had the following lines of code:
FileInputStream fis = new FileInputStream(this.initialExaminationFile);
//System.out.println(file.exists() + "!!");
//InputStream in = resource.openStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum); //no doubt here is 0
//Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
System.out.println("read " + readNum + " bytes,");
}
this.reportBytes = buf;
}
I converted my file into bytearraystream and made it available in my session. Then I followed the suggestion given by BalusC at Unable to show PDF in p:media generated from streamed content in Primefaces

Some pdf file watermark does not show using iText

Our company using iText to stamp some watermark text (not image) on some pdf forms. I noticed 95% forms shows watermark correctly, about 5% does not. I tested, copy 2 original pdf files, one was marked ok, other one does not ok, then tested in via a small program, same result: one got marked, the other does not. I then tried the latest version of iText jar file (version 5.0.6), same thing. I checked pdf file properties, security settings etc, seems nothing shows any hint. The result file does changed size and markd "changed by iText version...." after executed program.
Here is the sample watermark code (using itext jar version 2.1.7), note topText, mainText, bottonText parameters passed in, make 3 lines of watermarks show in the pdf as watermark.
Any help appreciated !!
public class WatermarkGenerator {
private static int TEXT_TILT_ANGLE = 25;
private static Color MEDIUM_GRAY = new Color(160, 160, 160);
private static int SUPPORT_FONT_SIZE = 42;
private static int PRIMARY_FONT_SIZE = 54;
public static void addWaterMark(InputStream pdfInputStream,
OutputStream outputStream, String topText,
String mainText, String bottomText) throws Exception {
PdfReader reader = new PdfReader(pdfInputStream);
int numPages = reader.getNumberOfPages();
// Create a stamper that will copy the document to the output
// stream.
PdfStamper stamp = new PdfStamper(reader, outputStream);
int page=1;
BaseFont baseFont =
BaseFont.createFont(BaseFont.HELVETICA_BOLDOBLIQUE,
BaseFont.WINANSI, BaseFont.EMBEDDED);
float width;
float height;
while (page <= numPages) {
PdfContentByte cb = stamp.getOverContent(page);
height = reader.getPageSizeWithRotation(page).getHeight() / 2;
width = reader.getPageSizeWithRotation(page).getWidth() / 2;
cb = stamp.getUnderContent(page);
cb.saveState();
cb.setColorFill(MEDIUM_GRAY);
// Top Text
cb.beginText();
cb.setFontAndSize(baseFont, SUPPORT_FONT_SIZE);
cb.showTextAligned(Element.ALIGN_CENTER, topText, width,
height+PRIMARY_FONT_SIZE+16, TEXT_TILT_ANGLE);
cb.endText();
// Primary Text
cb.beginText();
cb.setFontAndSize(baseFont, PRIMARY_FONT_SIZE);
cb.showTextAligned(Element.ALIGN_CENTER, mainText, width,
height, TEXT_TILT_ANGLE);
cb.endText();
// Bottom Text
cb.beginText();
cb.setFontAndSize(baseFont, SUPPORT_FONT_SIZE);
cb.showTextAligned(Element.ALIGN_CENTER, bottomText, width,
height-PRIMARY_FONT_SIZE-6, TEXT_TILT_ANGLE);
cb.endText();
cb.restoreState();
page++;
}
stamp.close();
}
}
We solved problem by change Adobe LifecycleSave file option. File->Save->properties->Save as, then look at Save as type, default is Acrobat 7.0.5 Dynamic PDF Form File, we changed to use 7.0.5 Static PDF Form File (actually any static one will work). File saved in static one do not have this watermark disappear problem. Thanks Mark for pointing to the right direction.
You're using the underContent rather than the overContent. Don't do that. It leaves you at the mercy of big, white-filled rectangles that some folks insist on drawing first thing. It's a hold over from less-than-good PostScript interpreters and hasn't been necessary for Many Years.
Okay, having viewed your PDF, I can see the problem is that this is an XFA-based form (from LiveCycle Designer). Acrobat can (and often does) rebuild the entire file based on the XFA (a type of xml) it contains. That's how your changes are lost. When Acrobat rebuilds the PDF from the XFA, all the existing PDF information is pitched, including your watermark.
The only way to get this to work would be to define the watermark as part of the XFA file contained in the PDF.
Detecting these forms isn't all that hard:
PdfReader reader = new PdfReader(...);
AcroFields acFields = reader.getAcroFields();
XfaForm xfaForm = acFields.getXfaForm();
if (xfaForm != null && xfaForm.isXfaPresent()) {
// Ohs nose.
throw new ItsATrapException("We can't repel XML of that magnitude!");
}
Modifying them on the other hand could be Quite Challenging, but here's the specs.
Once you've figured out what needs to be changed, it's a simple matter of XML manipulation... but that "figure it out" part could be interesting.
Good hunting.