Generate PDF from gsp page - pdf

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.

Related

Why is flying saucer always printing PDF on A4 paper?

I'm trying to save an html document to PDF using flyingsaucer but the generated document always ends up having an A4 dimension when I look at the Document Properties from Adobe Reader (Page Size: 8.26 x 11.69 in).
I did read the documentation and I'm passing the css #page {size: letter;} style. And while it does have an effect on the output, the page size always remains 8.26 x 11.69 in Adobe Reader. For example, if I set the page size to legal, my PDF is still the size of a A4 but the top of the document is missing as if it had fell off the "paper".
I'm not sure if the problem falls on the itext side or the flying saucer side. I was using a fairly old version so my first step was to upgrade to the latest 9.1.6 version of flying saucer. I also moved from itext 2.0.8 to openPDF 1.0.1 but I'm still getting the same behavior.
I also traced in the debugger up to the com.lowagie.text.Document creation in ITextRenderer and at this point the document size passed is correct. That makes me think that the issue might be in openPDF / iText but I can't find what I'm doing wrong.
It turns out the PDF generation was correctly using the #page size declaration and the problem was occurring later in our software. What I had not noticed is that after the generation of the PDF another method was called to merge multiple PDFs into one. This method should probably not have been called, but that's another story.
The bottom line is this method created a new com.lowagie.text.Document(), which by default creates an A4 sized document, and then was iterating over all pages of the pdf, adding the pages to the new document using pdfWriter.getImportedPage(pdfReader, currentPage++). These imported pages did not retain their original size.
I fixed it by passing the page size of the fist page when creating the merged document object:
document = new Document(pdfReader.getPageSize(1));
The real problem is that you're (unwittingly) using software that is no longer supported. Anything that still has the namespace lowagie (the founder and CTO of iText) is really outdated.
If you simply want to convert HTML to pdf, why not use iText directly and cut out the middle-man?
We have multiple options for you.
XMLWorker (iText5 based code that converts HTML to pdf)
pdfHTML (iText7 based add-on that converts HTML5/CSS3 to pdf)
This is a rather extensive code-sample for using pdfHTML:
public void createPdf(String src, String dest, String resources) throws IOException {
try {
FileOutputStream outputStream = new FileOutputStream(dest);
WriterProperties writerProperties = new WriterProperties();
//Add metadata
writerProperties.addXmpMetadata();
PdfWriter pdfWriter = new PdfWriter(outputStream, writerProperties);
PdfDocument pdfDoc = new PdfDocument(pdfWriter);
pdfDoc.getCatalog().setLang(new PdfString("en-US"));
//Set the document to be tagged
pdfDoc.setTagged();
pdfDoc.getCatalog().setViewerPreferences(new PdfViewerPreferences().setDisplayDocTitle(true));
//Set meta tags
PdfDocumentInfo pdfMetaData = pdfDoc.getDocumentInfo();
pdfMetaData.setAuthor("Joris Schellekens");
pdfMetaData.addCreationDate();
pdfMetaData.getProducer();
pdfMetaData.setCreator("iText Software");
pdfMetaData.setKeywords("example, accessibility");
pdfMetaData.setSubject("PDF accessibility");
//Title is derived from html
// pdf conversion
ConverterProperties props = new ConverterProperties();
FontProvider fp = new FontProvider();
fp.addStandardPdfFonts();
fp.addDirectory(resources);//The noto-nashk font file (.ttf extension) is placed in the resources
props.setFontProvider(fp);
props.setBaseUri(resources);
//Setup custom tagworker factory for better tagging of headers
DefaultTagWorkerFactory tagWorkerFactory = new AccessibilityTagWorkerFactory();
props.setTagWorkerFactory(tagWorkerFactory);
HtmlConverter.convertToPdf(new FileInputStream(src), pdfDoc, props);
pdfDoc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
You can find more information at http://itextpdf.com/itext7/pdfHTML

Dynamic XFA PDF Forms

I have a number of Dynamic XFA PDFs that were created with Livecycle Designer. These PDFs are used as templates for various individuals to complete. When a user requests a template we have to write a submit button with url pointing back to a .net application for processing and update some of the fields with information from the database into the PDF.
Can I use iText(Sharp) with .net to update the dynamic xfa pdf to write into it a submit button and update fields and then use iText(Sharp) to process the returning form.
We are doing this now with Acroforms but need to do the same for Dynamic XFA forms as well. I can’t find any confirmation information that this is possible. If it is possible does anyone have any code that they can share to show me how to do this?
You can also achieve that putting the pdf's content inside an XmlDocument and working as you were working with an XML.
This is the code I use to replace some placeholders written in textboxes.
PdfReader pdfReader = new PdfReader(path_pdf);
using (PdfStamper pdfStamp = new PdfStamper(pdfReader, new FileStream(temp_path, FileMode.Create), '\0', true))
{
pdfStamp.ViewerPreferences = PdfWriter.AllowModifyContents;
XmlDocument xmlDocument = pdfReader.AcroFields.Xfa.DomDocument;
string pdfContent = xmlDocument.InnerXml;
string newpdfContent = pdfContent
.Replace("$CONTENT_TO_REPLACE_1$", "some_content")
.Replace("$CONTENT_TO_REPLACE_2$", "some_other_content")
xmlDocument.InnerXml = newpdfContent;
Stream stream = GenerateStreamFromString(newpdfContent);
pdfStamp.AcroFields.Xfa.FillXfaForm(stream);
pdfStamp.AcroFields.Xfa.DomDocument = xmlDocument;
pdfStamp.Close();
}

In iTextSharp, how to include an existing PDF while creating a new document

I've found many solutions in here and in the 'iText in Action' book, to merge PDF's using the PDFCopy and PDFSmartCopy classes, but the only similar question asked I've seen, the guy worked it out himself but didn't post the answer. This post Add an existing PDF from file to an unwritten document using iTextSharp asks the same question but its at the end, so they suggest closing the existing document and then use PDFCopy, here I'd like to insert it anywhere. So here goes.
I'm creating an iTextSharp document with text and images using normal Sections, Phrases, Document and PDFWriter classes. This is code written over many years and works fine. Now we need to insert an existing PDF while creating this document as either a new Section or Chapter if that isn't possible. I have the PDF as a Byte array, so no problems getting a PDFReader. However, I cannot work out how to read that PDF and insert it into the existing document at the point I'm at. I can get access to the PDFWriter if need be, but for the rest of the document all access is via Sections. This is as far as I've got and I can add the PDFWriter as another parameter if necessary.
I've made some progress since the original post and amend the code accordingly.
internal static void InsertPDF( Section section, Byte[] pdf )
{
this.document.NewPage();
PdfReader pdfreader = new PdfReader( pdf );
Int32 pages = pdfreader.NumberOfPages;
for ( Int32 page = 1; page <= pages; page++ )
{
PdfImportedPage page = this.writer.GetImportedPage( planreader, pagenum );
PdfContentByte pcb = this.writer.DirectContentUnder;
pcb.AddTemplate( page, 0, 0 );
this.document.NewPage();
}
}
It is close to doing what I want, but as I obviously don't understand the full workings of iText wonder if this is the correct way or there is a better way to do it.
If there is any other information I can provide, let me know.
Any pointers would be appreciated.
Just adding a little more meat to the answer. The solution ended up being found by researching what methods worked with a PdfTemplate which is what a PdfImportedPage is derived from. I've added a little more to show how it interacts with the rest of the document being built up. I hope this helps someone else.
internal static void InsertPDF( PdfWriter writer, Document document, Section section, Byte[] pdf )
{
Paragraph para = new Paragraph();
// Add note to show blank page is intentional
para.Add( new Phrase( "PDF follows on the next page.", <your font> ) );
section.Add( para );
// Need to update the document so we render this page.
document.Add( section );
PdfReader reader = new PdfReader( pdf );
PdfContentByte pcb = writer.DirectContentUnder;
Int32 pages = planreader.NumberOfPages;
for ( Int32 pagenum = 1; pagenum <= pages; pagenum++ )
{
document.NewPage();
PdfImportedPage page = writer.GetImportedPage( reader, pagenum );
// Render their page in our document.
pcb.AddTemplate( page, 0, 0 );
}
}
for insert existing pdf into new page, i've change order newpage
PdfImportedPage page2 = writer.GetImportedPage(pdf, 1);
cb.AddTemplate(page2, 0, 0);
document.NewPage();

Java Image to PDF

How can an image file be converted into a PDF file using java? I am taking output from a graphic library. the output that I am able to export is in image formats like JPEG and PNG.
I want to convert that image file to PDF file.
You can use Itext to add an Image to a PDF.
Use IText PDF API for Java you must first download the IText JAR file from the IText website
First a Document instance is created.
Second, a PDFWriter is created, passing the Document instance and an OutputStream to its constructor. The Document instance is the document we are currently adding content to. The OutputStream is where the generated PDF document is written to.
OutputStream file = newFileOutputStream(newFile("/path/JavaGeneratedPDF.pdf"));
Document document = new Document();
PdfWriter.getInstance(document, file);
Here make sure that you handle DocumentException
Inserting Image in PDF
Image image = Image.getInstance ("/Image.jpg");
image.scaleAbsolute(200f, 100f); //image width,height
Here make sure that you handle MalformedURLException
Now Open PDF document, add image and close document instance
document.open();
document.add(image);
document.close();
file.close();

Adding a dynamic image to a PDF using ColdFusion and iText

I pieced together some code to insert a dynamic image into a PDF using both ColdFusion and iText, while filling in some form fields as well. After I got it working and blogged about it, I couldn't help but think that there might be a better way to accomplish this. I'm using the basic idea of this in a production app right now so any comments or suggestion would be most welcomed.
<cfscript>
// full path to PDF you want to add image to
readPDF = expandpath(”your.pdf”);
// full path to the PDF we will output. Using creatUUID() to create
// a unique file name so we can delete it afterwards
writePDF = expandpath(”#createUUID()#.pdf”);
// full path to the image you want to add
yourimage = expandpath(”dynamic_image.jpg”);
// JAVA STUFF!!!
// output buffer to write PDF
fileIO = createObject(”java”,”java.io.FileOutputStream”).init(writePDF);
// reader to read our PDF
reader = createObject(”java”,”com.lowagie.text.pdf.PdfReader”).init(readPDF);
// stamper so we can modify our existing PDF
stamper = createObject(”java”,”com.lowagie.text.pdf.PdfStamper”).init(reader, fileIO);
// get the content of our existing PDF
content = stamper.getOverContent(reader.getNumberOfPages());
// create an image object so we can add our dynamic image to our PDF
image = createobject(”java”, “com.lowagie.text.Image”);
// get the form fields
pdfForm = stamper.getAcroFields();
// setting a value to our form field
pdfForm.setField(”our_field”, “whatever you want to put here”);
// initalize our image
img = image.getInstance(yourimage);
// centering our image top center of our existing PDF with a little margin from the top
x = (reader.getPageSize(1).width() - img.scaledWidth()) - 50;
y = (reader.getPageSize(1).height() - img.scaledHeight()) / 2 ;
// now we assign the position to our image
img.setAbsolutePosition(javacast(”float”, y),javacast(”float”, x));
// add our image to the existing PDF
content.addImage(img);
// flattern our form so our values show
stamper.setFormFlattening(true);
// close the stamper and output our new PDF
stamper.close();
// close the reader
reader.close();
</cfscript>
<!— write out new PDF to the browser —>
<cfcontent type=”application/pdf” file = “#writePDF#” deleteFile = “yes”>
<cfpdf> + DDX seems possible.
See http://forums.adobe.com/thread/332697
I have made it in another way with itext library
I don´t want overwrite my existing pdf with the image to insert, so just modify the original pdf inserting the image, just insert with itext doesn´t work for me.
So, I have to insert the image into a blank pdf (http://itextpdf.com/examples/iia.php?id=59)
And then join my original pdf and the new pdf-image. Obtaining one pdf with several pages.
(http://itextpdf.com/examples/iia.php?id=110)
After that you can overlay the pdf pages with this cool concept
http://itextpdf.com/examples/iia.php?id=113