How can I convert a web form to pdf using itextsharp? - pdf

I am trying to convert a web form to a pdf after a user fills in the fields in the web form. Is this possible? All i can do right now is loop through the form collection and print out the field name and the field value to the pdf. Is there a way to do this and keep the pdf looking like the web form?
I'm using mvc 3 for the web page.
Thanks!
Now I am using the following which converts everything in the form but the form fields.
Document doc = new Document();
String path = "C:\\projects\\pdfs\\";
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(path + "Doc1.pdf", FileMode.Create));
StringReader sr = new StringReader(htmlString);
HTMLWorker worker = new HTMLWorker(doc);
doc.Open();
worker.Parse(sr);
doc.Close();
How do I get the form fields to display in the pdf?

Related

Replace a page in a PDF with iText7

I am in the process of updating some PDF editing tools from iTextSharp to iText7.
In iTextSharp there was a method in the pdfStamper class: pdfStamper.ReplacePage().
However, the pdfStamper class has been removed in iText7 and I am having trouble replicating the same functionality.
Say I have document X that needs page 4 replaced with page 1 of document Y but I want the result to be save to a new document Z.
So far I have 3 lines that use the CopyPageTo method. However any PDF document that gets created is only 1kb in size and corrupted.
Anyone have experience with the newer iText7 and the CopyPageTo method?
NewPagesReader = New PdfReader(strNewPageDocPath)
docNewPages = New PdfDocument(NewPagesReader)
OriginalDocReader = New PdfReader(strOrigPageDocPath)
docOringal = New PdfDocument(OriginalDocReader)
Dim docNew As PdfDocument
Dim NewPDFWriter As New PdfWriter(saver.FileName)
docNew = New PdfDocument(NewPDFWriter)
docOringal.CopyPagesTo(1, 3, docNew)
docNewPages.CopyPagesTo(1, 1, docNew)
docOringal.CopyPagesTo(5, 6, docNew)
ToWriter.Close()
docNew.Close()
Your code looks fine. Instead of copying all the pages to a new document, you can also delete and insert a page:
NewPagesReader = New PdfReader(strNewPageDocPath)
docNewPages = New PdfDocument(NewPagesReader)
OriginalDocReader = New PdfReader(strOrigPageDocPath)
Dim NewPDFWriter As New PdfWriter(saver.FileName)
docOringal = New PdfDocument(OriginalDocReader, NewPDFWriter)
docOringal.RemovePage(4)
docNewPages.CopyPagesTo(1, 1, docOringal, 4)
docOringal.Close()

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.

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();
}

iText-merged editable PDF loses form data when Acrobat Pro saves as separate PDF

We're replacing Adobe LiveCycle Server with iText 5.4.1 in an existing webapp to merge XML data with LiveCycle Designer-generated PDF templates, generating editable PDF files from several hundred templates.
This code combines the data with the template, returning a PDF byte array:
// Import data into the PDF form
if (pdfTemplateFileName != null && inputXmlDataFile != null) {
// set up the objects
template = new PdfReader(pdfTemplateFileName);
filledPDF = new ByteArrayOutputStream();
stamper = new PdfStamper(template, filledPDF);
AcroFields form = stamper.getAcroFields();
// fill in the form with the data
XfaForm xfa = form.getXfa();
xfa.fillXfaForm(inputXmlDataFile);
//closing the stamper is necessary to flush to filledPDF
stamper.close();
returnPDF = filledPDF.toByteArray();
}
This code combines the PDF byte arrays into a portfolio:
List<byte[]> assemblingPdfList = assemblingPdfMap.get("newStyleForms");
// create PDF portfolio of editable documents
com.itextpdf.text.Document document = new com.itextpdf.text.Document();
ByteArrayOutputStream mergedPDFOutput = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, mergedPDFOutput);
document.open();
Paragraph coverSheet = new Paragraph("Multiple files are bound together in this PDF Package");
coverSheet.setAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
document.add(coverSheet);
// define the collection
PdfCollection collection = new PdfCollection(PdfCollection.DETAILS);
PdfCollectionSchema schema = new PdfCollectionSchema();
PdfCollectionField filename = new PdfCollectionField("Name", PdfCollectionField.FILENAME);
filename.setOrder(0);
schema.addField("FILENAME", filename);
PdfCollectionField description = new PdfCollectionField("Description", PdfCollectionField.TEXT);
description.setOrder(1);
schema.addField("DESCRIPTION", description);
PdfCollectionField modified = new PdfCollectionField("Modified", PdfCollectionField.MODDATE);
modified.setOrder(2);
schema.addField("MODIFIED", modified);
PdfCollectionField size = new PdfCollectionField("Size", PdfCollectionField.SIZE);
size.setOrder(3);
schema.addField("SIZE", size);
collection.setSchema(schema);
writer.setCollection(collection);
// loop through the PDF documents and add each to the portfolio
PdfFileSpecification fs;
PdfCollectionItem item;
int iNum = 0;
for (byte[] pdf : assemblingPdfList) {
fs = PdfFileSpecification.fileEmbedded(writer, null,
String.format("StylesResult_%s.pdf", iNum++), pdf);
fs.addDescription("Styles Result File", false);
item = new PdfCollectionItem(schema);
item.addItem("DESCRIPTION", "Styles Result File");
item.addItem("MODIFIED", new PdfDate() );
fs.addCollectionItem(item);
writer.addFileAttachment(fs);
}
// close document
document.close();
mergedPDFOutput.flush();
mergedPDFOutput.close();
return mergedPDFOutput.toByteArray();
At first, iText would not populate the form fields. We used LiveCycle Designer to change the data binding of most fields from Normal to Global, which enabled iText to populate most of them correctly. The exception were the repeating (think 'table') rows of data; setting the binding to 'Global' caused the first data value to be repeated down the column for each of the data records. Setting the repeating fields' bindings back to 'Normal' seemed to work.
The iText-merged editable PDF portfolios are launched in Internet Explorer 10. If we click 'Open File' to open an individual PDF in Adobe Acrobat XI Pro, all the data is there. However, if we click 'File' / 'Save As' in Acrobat Pro to save to a new PDF file, then open the new file, some or all of the form data has disappeared (In one case, the 'first generation' save left most of the data intact, but repeating subform data was erased. Saving again, creating a 'second generation' save, erased all data.)
My failed solution attempts include: (a) initializing PdfStamper in 'append' mode; (b) Modifying my PdfStamper with 'stamper.setEncryption(false, "", "", PdfWriter.ALLOW_{everything}...)'.
Adobe LiveCycle Server-generated portfolios do not lose data, no matter how many generations of saves are made.

Print one page of WebBrowser

I am trying to automate printing of intranet websites. Since this is an application that will be put on a specific user's computer, which will be run on an as-needed basis, I'd like it to be as un-disruptive as possible (in other words, not launching IE for each page). The catch is that I need to print the first page of the website and then print the whole website again, which will produce the first page two times. What is the best way to do this?
I have no problem getting it to loop through the pages that it needs to print, nor do I have a problem opening the page with webbrowser. I do, however, have a problem specifying a print range.
I also tried PrintDocument, but couldn't figure out how to get that to open within the form.
Thanks for any help that can be provided.
To download the pdf file, try this solution using iTextSharp:
ITextSharp HTML to PDF?
Except with one substitution if you want to save directly to a file
private MemoryStream createPDF(string html)
{
MemoryStream msOutput = new MemoryStream();
TextReader reader = new StringReader(html);
// step 1: creation of a document-object
Document document = new Document(PageSize.A4, 30, 30, 30, 30);
// step 2:
// we create a writer that listens to the document
// and directs a XML-stream to a file
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("c:\\my.pdf", FileMode.Create));
// step 3: we create a worker parse the document
HTMLWorker worker = new HTMLWorker(document);
// step 4: we open document and start the worker on the document
document.Open();
worker.StartDocument();
// step 5: parse the html into the document
worker.Parse(reader);
// step 6: close the document and the worker
worker.EndDocument();
worker.Close();
document.Close();
return msOutput;
}
Once the PDF is set up, try ghostscript to print one page:
Print existing PDF (or other files) in C#
If you start a shell execute of the process, you can use the command line arguments:
gsprint "filename.pdf" -from 1 - to 1
Alternatively, WebBrowser can just print the full page: http://msdn.microsoft.com/en-us/library/b0wes9a3.aspx
I can't find anything referencing that WebBrowser itself can print "From page X to Y" without a print dialog.
Since I'm facing a similar problem, here's an alternate solution:
This open source project turns HTML documents to PDF documents similar to iTextSharp (http://code.google.com/p/wkhtmltopdf/). We ended up not using iTextSharp because of several formatting issues with the way the site we wanted to print was laid out. We send command line arguments to turn the html downloaded using a webclient into a pdf file.
WebClient wc = new WebClient();
wc.Credentials = CredentialCache.DefaultNetworkCredentials;
string htmlText = wc.DownloadString("http://websitehere.com);
Then, after turning to pdf, you can simply print the file:
Process p = new Process();
p.StartInfo.FileName = string.Format("{0}.pdf", fileLocation);
p.StartInfo.Verb = "Print";
p.Start();
p.WaitForExit();
(Apologies for C#, I'm more familiar with it than VB.NET, though it should be a simple conversion)