Tech Off Thread

80 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

Conversation Locked

This conversation has been locked by the site admins. No new comments can be made.

ASP.NET and iTextSharp (free PDF Generator for .NET)

Back to Forum: Tech Off
  • User profile image
    sbc

    Anyone use iTextSharp to create PDF's containing form fields? It is for a form that is generated from a database and one that the user can fill in (to print and send, or email).

    I can generate the PDF from the database, but have no idea how to add text boxes, checkboxes etc. The tutorials don't seem to cover that.

    Ideally I'd want to convert a HTML web page to a PDF, but I don't think that is possible (with any freely available components), especially when using it on a shared hosting service (the options I have seen include installing software on the server, then running that and returning the file).

  • User profile image
    johan_london

    I had similar problem. I just downloaded a trial of the latest version of the Adobe Acrobat, which has a cool form designer tool. I used that to create the template document for my program, including adding all the form fields.

    This works fine as long as you do not need to modify the template after it is created.

    My code then creates the PDF documents based on this template, by filling in values from database records, into form fields programmatically.

    Good luck...

  • User profile image
    sbc

    Any example of doing this? I have Acrobat 5, so can create the PDF.

    How do you then use iTextSharp to modify the fields (i.e. do you have any example code)?

    Apart from iTextSharp, the tools that generate the PDF's are quite expensive (also, I can only use free components). iTextdotNET uses J#, so I can't use that (but I don't think it offers anything over iTextSharp).

  • User profile image
    johan_london

    OK, let's say I have a PDF document called "Form.pdf" with 4 form fields. The form fileds are "name", "address", "postal_code" and "email".

    Here's the code to create a new PDF file using "Form.pdf" as a template:

    private void fillForm()
    {
        string formFile = @"N:\.NET\Form.pdf";
        string newFile = @"N:\.NET\Filled-out Form.pdf";
        PdfReader reader = new PdfReader(formFile);
        PdfStamper stamper = new PdfStamper(reader, new FileStream(
                    newFile, FileMode.Create));
        AcroFields fields = stamper.AcroFields;

        // set form fields
        fields.SetField("name", "John Doe");
        fields.SetField("address", "2 Milky Way, London");
        fields.SetField("postal_code", "XX1 4YY");
        fields.SetField("email", "johndoe@hotmail.com");

        // flatten form fields and close document
        stamper.FormFlattening = true;
        stamper.Close();
    }

    Acrobat 5 should be enough to create a PDF form. Let me know if you're having any troubles.

  • User profile image
    sbc

    Thanks, that worked out fine. Pity the documentation is not that good, but as a side effect I found out about generating a document from Xml or via document.Add.

    Only difference is I used Server.MapPath to get the file, and saved the 'stamped' document to a MemoryStream that is then streamed to the user. Didn't use FormFlattening either - what is the advantage of using it?

    Also, how do you change author, subject, keywords etc using PdfStamper/Reader?

  • User profile image
    johan_london

    sbc wrote:
    Thanks, that worked out fine. Pity the documentation is not that good, but as a side effect I found out about generating a document from Xml or via document.Add.

    Only difference is I used Server.MapPath to get the file, and saved the 'stamped' document to a MemoryStream that is then streamed to the user. Didn't use FormFlattening either - what is the advantage of using it?

    Also, how do you change author, subject, keywords etc using PdfStamper/Reader?



    Form Flattening flettens the actual form fields so that they can no longer be changed in the new document created by the stamper. If you have not set that, anyone can change the contents of the form fields... If you do specify Form Flattening, then the form fields will be converted into text and cannot be further modified.

    To add the document meta-data, you would normally use the following methods of the Document object (before calling document.Open()):

    private void createPDF()
    {
       string newFile = @"N:\.NET\New Document.pdf";
       Document doc = new Document();
       PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(newFile, FileMode.Create));
       // Metadata
       doc.AddCreator("PDF Printer by Joachim Tesznar");
       doc.AddTitle("New PDF Document");
       // Add content
       doc.Open();
       doc.Add(new Paragraph("Hello World"));
       doc.Close();
    }

    I don't know how you can do this using the PdfStamper object; there must be a way of accessing the document object in-directly. If you find out how, let me know... Wink If you can't, I know a way around this but it requires copying the ContentByte of that document and importing a page into a new document where you can set the meta-data.

    Another option is to create your document in XML (see the tutorial), then use the XmlParser object to convert it to PDF. You can set your meta-data in the XML document and the parser will set these in the PDF for you.

    Have fun

  • User profile image
    johan_london

    Once you created the PDF file using the PdfStamper object, you can set the document properties by importing the file into a new document - where you can set properties such as Author and Title.

    Note, the following code is just a workaround (not a solution):

    using System.IO;
    using iTextSharp.text;
    using iTextSharp.text.pdf;

    public static void CopyDocumentTest()
    {
       int pageNumber = 1;
       PdfReader reader = new PdfReader("New Document.pdf");
       Rectangle size = reader.GetPageSizeWithRotation(pageNumber);
       Document document = new Document(size);
       PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("Copy of New Document.pdf", FileMode.Create, FileAccess.Write));

       //set document info
       document.AddTitle("Document copied using iTextSharp");
       document.AddAuthor("Joachim Tesznar");
       document.AddSubject("Dynamic Content");
       document.AddCreator("PDF Form Tool by Joachim Tesznar");

       document.Open();

       PdfContentByte cb = writer.DirectContent;
       document.NewPage();
       PdfImportedPage page = writer.GetImportedPage(reader, pageNumber);
       cb.AddTemplate(page, 0, 0);
       document.Close();
    }

  • User profile image
    sbc

    I looked at XML, but it seems as though it does not have the required tags for creating forms. Plus it is probably far easier to do the document in Word, then convert to PDF and add the form fields using Acrobat.

    It looks like the steps I have to take are:

    - Use PdfReader to get the original PDF.

    - Use PdfStamper to edit the form fields, save into a MemoryStream.

    - Populate a PdfWriter document from the PdfStamper (which actually contains PdfStamper.Writer, but I dont think you can access the document part of it). Save into MemoryStream which is then sent to the user.

    Don't know why you have to go through all those stages just to modify a file (only need the first two if you don't need to change the title). The last stage seems as though it would be inefficient.

    Although PdfStamper does have a SetMoreInfo method that may be able to change the meta information (at least in iText, not checked if iTextSharp has this).

    Pity there are no iTextSharp forums to ask on.

  • User profile image
    johan_london

    sbc wrote:
    Don't know why you have to go through all those stages just to modify a file


    You don't; like I said it's just a workaround. And yes, it's inefficient (especially if you're doing it on the server).

    But if it is just the Title you are worries about, then just set the title on the form template and when the new document is created with the stamper, the Title will still be there.

  • User profile image
    sbc

    Here is what I will try that may work (won't be able to do it till tomorrow though). Pseudo code:

    HashMap info = stamper.GetMoreInfo();
    info["Title"] = "New Title";
    info["Creator"] = "Web page";
    stamper.SetMoreInfo(info);

    Hopefully that will be all I need to do.

  • User profile image
    sbc

    Managed to modify the data using the following:

    Hashtable info = new Hashtable();
    info["Title"] = "Modified Form";
    info["Author"] = "Fred Bloggs";
    info["Creator"] = "My Web App";
    stamper.MoreInfo = info;

  • User profile image
    johan_london

    Nice work Smiley  thanks

  • User profile image
    craigsdennis

    So glad to finally find a forum where people are talking about this iTextSharp.  The documentation is next to useless.   I wrote pretty cool ASP.NET application that takes form input and then generates a PDF by taking the text of the fields on the form and pasting them to a template.
    So essentially I have our designer make the PDF template with the form fields formatted the way they should be with font and color and then we create it.  It's been working great until...our client decided that some of the dynamic text should have a CMYK color. 

    Until then we hadn't realized that our font colors were coming in grayscale.  Black and White of course work fine, but when we try this rich pink look it comes out gray.  Anyone have any idea how to change this.

    I poked around and found the SetDefaultColorSpace function, but I'm not sure what the second parameter is supposed to be.  And more importantly I'm not even sure it's how to change this.

    Anyone know?  I am using PDF stamper and form flattening would rather not have to take the approach of gathering all the field properties myself and reposting them, as that is what the Stamper is for.

    If you have any idea or even a place to look that has some sort of info other than the sourceforge page...please please let me know.

    Thanks,
    --Craig Dennis

  • User profile image
    johan_london

    Craig

    Have a look at the Java documentation; Java iText version is very different from the current iTextSharp version but the API is well documented in some places so might give you ideas (it's helped me). You can find it on http://itextdocs.lowagie.com/docs/.

    Are you trying to set the form fields font color using stamper? When I needed to have some dynamic text in color, I used the PdfContentByte object to create the text and then position it on the document, but not sure how would that work on the form with the stamper. Let us know.

    Have fun

  • User profile image
    craigsdennis

    FYI....Hey all so you know....I finally figured out the error.

    The Color.cs class had an error.

    The constructor that takes floats accidentally created a new RGB using the R 3 times, thus creating a gray effect much like #CCCCCC.  So....if you fix that it'll work, I told Paulo so should be fixed in the next iterim.

    Thanks,
    --Craig Dennis
    Rhino Internet
    http://www.rhinointernet.com

  • User profile image
    johan_london

    Nice one Craig, well done mate Smiley

  • User profile image
    rocko_hunk

    Hi guys,

    I am a newbie to iTextSharp,
    can anybody please send me the code for

    reading pdf Form fields and their values using iTextSharp

  • User profile image
    sbc

    This should work:

    C#

    // this is used to store the PDF in memory
    MemoryStream m = new MemoryStream();
    // which document to open
    string file = Server.MapPath("form.pdf");
    PdfReader reader = new PdfReader(file);
    // then create a PdfStamper from the created reader to modify the form fields
    PdfStamper outStamper = new PdfStamper(reader, m);
    string name = outStamper.AcroFields.GetField("name");

    VB.NET
    ' this is used to store the PDF in memory
    Dim m As MemoryStream = New MemoryStream()
    ' which document to open
    Dim file As String = Server.MapPath("form.pdf")
    Dim reader As PdfReader = New PdfReader(file)
    ' then create a PdfStamper from the created reader to modify the form fields
    Dim outStamper As PdfStamper = New PdfStamper(reader, m)
    Dim name As String = outStamper.AcroFields.GetField("name")

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.