Library code snippets
Dynamically Generating PDFs in .NET
It's perfectly possible to generate a PDF from scratch, using a library such as iTextSharp, a port of a free Java PDF library. However, it can be hard work defining all the code you need to generate the layout you're after, and impossible for someone to tweak the layout without going back to the developer.
One alternative, using the same free library, is instead to design a PDF document in a WYSIWYG environment such as Adobe Designer, and define some dynamic fields within the document. Your code can load this PDF form, set the value of each of the fields, and output a flat PDF. This would enable you to, for instance, have an invoice PDF template defined, set a bunch of fields within the PDF, and output as a flat PDF document - without needing a load of code generating the PDF from scratch.
The code itself is very straightforward. We're going to send the resulting output to the ASP.NET response stream, so we need to set the content-type and also a content-disposition header so that the result appears as a file download.
Response.ContentType = "application/pdf";
Response.AddHeader("Content-disposition", "attachment; filename=tokens.pdf");
Note that we could just as easily be using a file stream, and would therefore replace the above with opening a stream to the appropriate file path. With that out of the way, we use a PdfReader object to load our existing PDF from the local file system; in this case, from ~/assets/form.pdf.
PdfReader pdfReader = new PdfReader(Request.MapPath("~/assets/form.pdf"));
Next we create a PdfStamper object, which will allow us to modify the form fields defined in the PDF and save the result. We pass it the PdfReader object representing the PDF file, and a stream we want the result sent to. Finally, we set the FormFlattening flag so that we get a flat PDF rather than allowing the fields to remain editable.
PdfStamper pdfStamper = new PdfStamper(pdfReader, Response.OutputStream);
pdfStamper.FormFlattening = true; // generate a flat PDF
We can then set the dynamic fields defined within the PDF form, and close our pdfStamper object.
AcroFields pdfForm = pdfStamper.AcroFields;
pdfForm.SetField("InvoiceRef", "00000");
pdfForm.SetField("DeliveryAddress", "Oxford Street, London");
pdfForm.SetField("Email", "anon@anywhere.com");
pdfStamper.Close();
Closing the pdfStamper object results in the PDF being written to the stream we passed in the constructor, and we're all done. Simple!
Related articles
Related discussion
-
Binary Studio | software development outsourcing Ukraine
by shane124 (4 replies)
-
Chart insertation in a windows form...
by pdhanik (1 replies)
-
Point of Sale Developers: Hardware & C# SDK
by ManiGovindan (7 replies)
-
help with the remote frame buffer protocol from real VNC
by poison (0 replies)
-
Need help making a complete program editable, C# or .net I think
by davelee (1 replies)
Related podcasts
-
A Practical Look at Silverlight 2 Part 1
Now that Silverlight 2 is at the Olympics and making a big splash, we wanted to explore this fascinating technology more. Microsoft Silverlight 2 is a cross-browser, cross-platform, and cross-device plug-in for delivering the next generation of .NET based media experiences and rich interactive ap...
Events coming up
-
Nov
18
15 Minutes of Fame
Dresher, United States
This is a yearly tradition. We select 10 of the favorite speakers from monthly meetings, code camps, and hands on labs. Each one does a 15 minute talk on their favorite .NET technology. This is our 10th anniversary so we plan a gala event with special prizes and refreshments.
jsr solution the software developing company is going to organize an entrance test for free software training. the test is held on 14 November 2009 at quest institute of Chandigarh mohali (landra) . this test is absolutely free. and the students who will pass out this examination will get free software training. for the registrations please visit following link:- [url=http://training.jsrsolutions.com/registration.aspx] BTech Training[/url]
!--removed tag-->I realise this isn't exactly using .NET, but an excellent solution I've found in many cases is to use SQL Server Reporting Services for document generation. Of course, you have to know that your system has access to a reporting server but if you're building a system which will be used within a company's enterprise then this is likely.
Just thought it worth mentioning :0)
!--removed tag-->Just as an additional note for those of you using this to populate PDF templates that wish to retain the "Extend Features in Adobe Reader" option, you will need to use the following constructor when creating the PdfStamper object:
PdfStamper stamper = new PdfStamper(pdfReader, Response.OutputStream, '\0', true);
From the Java 1T3XT FAQ at http://1t3xt.info/tutorials/faq.php?branch=faq.itext&node=enabled_form.
!--removed tag-->Thanks
!--removed tag-->very good
No - you don't need Acrobat at all - just the iTextSharp library.
Hi,
So, to include this in an ASP.net web app, would I need to have Acrobat installed on the Web Server??
thanks
Steve S
SteveDotSchilzATsbcglobalDOTnet
I'm sure this isn't a great place to ask for a resolution to my itextsharp issues, but you seem to be the only person I've stumbled across who might know the answer (I'm sure you're well-aware that there is a serious dearth of documentation and information available about itextsharp otherwise).
We are doing much the same as your post suggests (using itextsharp to fill fields in a pre-defined PDF and send it down to the user user) and we have just about given up on being able to use itextsharp to fill a PDF form textbox with rich-text-encoded text and I was wondering if you might have any suggestions for us.
Acrobat makes it trivial to setup a textbox field in a PDF form to accept RTF content (just set the props on the field to 'use RTF text' in the forms designer) but when we use itextsharp to fill this field with RFT-encoded content, the RTF syntax is reproduced in its entirety with in the textbox in the PDF (e.g., we get '{\rtf\01\hello\etc....}' instead of the text with the formatting applied).
Have you (or anyone else who might view this blog post) ever tried this and come across the same issue? Other than this, we find itextsharp to be a quite useful tool for systems that need to collect data in one format (e.g., via a web form, a winform, whatever) and then display that back to the user in any pre-conceived format in an organizational-specific paper-form equivalent).
Happy coding to all~!
-Steve B.
This thread is for discussions of Dynamically Generating PDFs in .NET .