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
    Le Moustique

    Hello,

    I have 1 question ...

    In Itextsharp you can prompt the Printerfunction from the pdf file.

    But is it possible to change the printer settings of the pdf printfunction:

    - I need to have 2 pages on 1 paper.

    In the examples of Itextsharp is this the code to prompt the print settings.

    PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer);

    writer.AddJavaScript(jAction);


    You see, it is some Javascript to add the action.

    Can somebody help me out ?

    thanx

  • User profile image
    phejndorf

    This is a reply to the posting by "Filth" about empty PDF - "rocksky" has more or less the same solution.

    The trick is here:

                  stamp.FormFlattening = true;
                  // very important to keep the MemoryStream intact

                  stamp.Writer.CloseStream = false;

     
                  stamp.Close();

    It took me a good deal of head-scratching to find the solution a while back, and I've posted a blog-posting about it on my (infrequently updated)  blog:

    http://www.hejndorf.dk/persistent/?p=11


    Regards

  • User profile image
    fooey

    I created a PDF in Adobe Designer 7.0 with the usual text fields.

    I also added three RadioButtonList controls.

    Populating the PDF's text fields was trivial, but selecting a PDF radio button was not.

    I checked the iText (Java) documentation and found instructions. 

    Here's how in C#: 

    /* myRadioButton1 is what I named the Radio Button control in Adobe Designer. The "1", "2" etc. are the value automatically assigned by Adobe Designer. */

    fields.SetListOption("myRadioButton1", new String[] { "1", "2", "3", "4", "5", "6" }, null);

    /* this selects the second radio button. */

    fields.SetField("myRadioButton1", "2");

    I hope this helps someone else.

    tags: RadioButtonList Radio RadioButton SetListOption input type="radio"

  • User profile image
    cheong

    joachim wrote:
    rocsky wrote:

    you can get more information about iTextsharp tutorial(both C# version and VB.NET version ) from http://hardrock.cnblogs.com



    Yeah - as long as you can understand this:

    下类文件,为类构造函数增加了一个参数以便用户可以方便的在使用的时候设置配置文件路径,这样就可以把这个类包放置在任何可以被访问到的目录下,否则原来的版本下引用class.Chinese.php的文件必须和class在相同的目录下面才行。


    I think I might do it better:

    "Subclass document"(this is not sure) is class constructer that have additional parameter that allow users to convienently changing the defined document path. So you can put this class package in any directory you have access to. Otherwise to use the class in the origional version, files of Chinese.php must be placed in the same directory of the class.

    Recent Achievement unlocked: Code Avenger Tier 4/6: You see dead program. A lot!
    Last modified
  • User profile image
    reshminair

    Hi,
    I have a newbie question on ITextSharp.

    I have an input pdf file that I have to stamp with values from an XML document. Is it possible to do this with ITextSharp.

    I tried examples successfully where I could create PDF files from XML using XMLParser and I could stamp data into PDF files using PDFStamper.

    What I'm looking for is to stamp values into PDF files from a XML file, without having to parse out the XML input using custom code. Is that possible using ITextsharp?

    Thanks,
    Reshmi

  • User profile image
    shyamvchari

    I'm very glad to get across this forum. I have a question. Is it possible to add an image to a header using iTextSharp?

    Somebody pls, say yes and how Smiley

    Thanks
    Shyam

  • User profile image
    shyamvchari

    I figured it out myself few hrs. later. All i had to was, load an image into a chunk and then load the chunk into a phrase for header. Below is the code snippet.
      
      IText.Image image = IText.Image.GetInstance(@"C:\ImageLib\Header.jpg");
        image.ScalePercent(50.0F);
        IText.Chunk ck = new Chunk(image, 0F, 0F);
        
        HeaderFooter header = new HeaderFooter(new Phrase(ck), false);

    Thanks for all the minds that thought abt. a solution to my question.

  • User profile image
    factorh

    Hi,

    Im newly joined. Working on asp.net application. Have a requirement, there is an existing pdf file which i have to fill data to that pdf from database. How to read the pdf and identify the fields from the pdf. Can you plz. help me on this.

  • User profile image
    jaleelak

    Hi friends,

    I have a very special requirement with Itextsharp. Actually, I have Infopath form template(.xsn). When I fill it out and save , it is stored as >xml files. I need to convert this to .pdf files. I think , ItextSharp can help me.


    I got a code from http://www.ujihara.jp/iTextdotNET/en/examples.html  as shown here.When I run this , it creates pdf but no contents. I think step 3 has some problem. To convert XML, should I use XSL. Cna anybody help me in this....?

    public class Chap0704 
    {
      public static void Main(String[] args)
         {
                // step 1: creation of a document-object
                 Document documentA = new Document(PageSize.A4, 80, 50, 30, 65);
            
                   // step 1: creation of a document-object
                   Document documentB = new Document(PageSize.A4, 80, 50, 30, 65);
            
                   // step 2:
                   // we create a writer that listens to the document
                   // and directs a XML-stream to a file
                   PdfWriter.getInstance(documentA, new FileStream("Chap0704a.pdf", FileMode.Create));
                   PdfWriter.getInstance(documentB, new FileStream("Chap0704b.pdf", FileMode.Create));
            
                   // step 3: we parse the document
                   XmlParser.parse(documentA, "Chap0701.xml");
                 XmlParser.parse(documentB, "playRomeoJuliet.xml", "tagmapRomeoJuliet.xml");
            }
    }

    Thanks in advance....

  • User profile image
    flo2007

    Here is a .NET library that although is not free, it's not very expensive: ExpertPDF Html To Pdf Converter.

    Goodl uck

  • User profile image
    Fishern74

    Hi Jaleelak

    I have used an XSL file to transform an infopath xml into the required format for itextsharp to generate a PDF.  I have found that it works well for what I am doing.

    This code is not all mine as I copied it from one of the tutorials around the place.

    dim pdfFileName as string = "c:\temp\test.pdf"
    dim tmpTransformFile as string

    Private Sub PDFForm()
     Console.WriteLine("Create PDF")
     tmpTransformFile = IO.Path.Combine(IO.Path.GetTempPath, IO.Path.GetTempFileName)

     InfopathToIText(tmpTransformFile)
     createPDF(tmpTransformFile)

     Console.WriteLine("Finished PDF")
    End Sub

    Public Sub InfopathToIText(ByVal strFilename As String)
     Dim writer As XmlTextWriter
     Dim doc As XmlDocument
     Try
      doc = New XmlDocument
      doc.LoadXml(thisXDocument.DOM.xml)

      ' Modify the XML file.
      Dim root As XmlElement = doc.DocumentElement

      ' Create an XPathNavigator to use for the transform.
      Dim nav As XPath.XPathNavigator = root.CreateNavigator()

      ' Transform the file.
      Dim xslt As Xsl.XslTransform = New Xsl.XslTransform

      xslt.Load(config.GetValue("xslt-file"))
      writer = New XmlTextWriter(strFilename, Nothing)
      xslt.Transform(nav, Nothing, writer, Nothing)

     Catch ex As Exception
      Throw ex
     Finally
      Try
       If writer.WriteState <> WriteState.Closed Then writer.Close()
      Catch
       'ignore exception
      End Try
     End Try
    End Sub

    Public Sub createPDF(ByVal strFilename As String)

     ' step 1: creation of a document-object
     Dim _document As Document = New Document(PageSize.A4, 14, 14, 14, 14)
     Dim fs As FileStream
     Try

      ' step 2:
      ' we create a writer that listens to the document
      ' and directs a XML-stream to a file
      Dim ndInvoiceNo As DOMNode = thisXDocument.DOM.selectSingleNode("/my:myFields/my:invoiceNo")
      fs = New FileStream(pdfFileName, FileMode.Create)
      PdfWriter.GetInstance(_document, fs)

      ' step 3: we create a parser
      Dim h As iTextSharp.text.xml.ITextHandler = New iTextSharp.text.xml.ITextHandler(_document)

      ' step 4: we parse the document
      h.Parse(strFilename)

     Catch bee As iTextSharp.text.BadElementException
      Console.WriteLine(bee.Message)
      Console.WriteLine(bee.StackTrace)

      Throw New ApplicationException("There is a problem creating the PDF", bee)
     Catch e As Exception
      Console.WriteLine(e.Message)
      Console.WriteLine(e.StackTrace)

      Throw New ApplicationException("There is a problem creating the PDF", e)
     Finally
      Try
       _document.Close()
       _document = Nothing
       fs.Close()
      Catch
       'ignore exception
      End Try
     End Try
    End Sub


    Hope this helps

  • User profile image
    JBanta

    Filth said:

    Hi,

    I've just starting using iTextSharp in a code behind page, but when I run it, it just shows a empty pdf.

    I was wondering if anyone could see anything crazy that I have or haven't done?

    The code in my page_load event is:

    MemoryStream m = new MemoryStream();

    Document document = new Document(PageSize.A4.Rotate(), 10, 10, 10, 10);

    try

    {

    Response.ContentType = "application/pdf";

    PdfWriter.GetInstance(document, m);

    document.Open();

    document.Add(new Paragraph(DateTime.Now.ToString()));

    document.Add(new Paragraph("This is another test"));

    document.Add(new Paragraph("Yet another test"));

    }

    catch (DocumentException ex)

    {

    Console.Error.WriteLine(ex.StackTrace);

    Console.Error.WriteLine(ex.Message);

    }

    // step 5: Close document

    document.Close();

    // step 6: Write pdf bytes to outputstream

    Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length);

    Response.OutputStream.Flush();

    Response.OutputStream.Close();

    You are trying to use iTextSharp in a web application so you can use ASP.NET's response stream directly to write the PDF.  Your code would look something like:

                this.Response.ContentType = "application/pdf";

                Document doc = new Document();

                PdfWriter writer = PdfWriter.GetInstance( doc, this.Response.OutputStream );

                try
                {
                    doc.Open();
                    doc.Add( new Paragraph( DateTime.Now.ToString() ) );
                    doc.Add( new Paragraph( "This is a test" ) );
                }
                finally
                {
                    doc.Close();
                    writer.Close();
                }

  • User profile image
    chint

    sbc said:
    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.

    Can you tell me how to write pdf contents to word doc.

  • User profile image
    jh71283

    JBanta said:
    Filth said:
    *snip*
    You are trying to use iTextSharp in a web application so you can use ASP.NET's response stream directly to write the PDF.  Your code would look something like:

                this.Response.ContentType = "application/pdf";

                Document doc = new Document();

                PdfWriter writer = PdfWriter.GetInstance( doc, this.Response.OutputStream );

                try
                {
                    doc.Open();
                    doc.Add( new Paragraph( DateTime.Now.ToString() ) );
                    doc.Add( new Paragraph( "This is a test" ) );
                }
                finally
                {
                    doc.Close();
                    writer.Close();
                }
    You are resurrecting a thread over a yr old.

    Chances are the problem has been solved by now...

  • User profile image
    Prashanth

    joachim said:
    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.

    Hi , 
    i want to insert an image into PDF dynamically.
    I have a XML as input  and used dtd for formatting it which and iam using XMLparser to parse the xml with hash table.
    similar to this link has http://www.ridgway.co.za/archive/2005/07/31/itextsharpxmltopdfexample.aspx

    Here is the code i had

    Document document = new Document();
    MemoryStream m = new MemoryStream();
    System.Collections.Hashtable tagmap = new Hashtable();

    XmlPeer peer = new XmlPeer(ElementTags.CHUNK, "EmployeeName");
    peer.Content = "CandidateFirstName ";
    tagmap.Add(peer.Alias, peer);

    XmlParser.Parse(document, HttpContext.Current.Server.MapPath("~/sample.xml"), tagmap);

    Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length);
    Response.OutputStream.Flush();
    Response.OutputStream.Close();

    The above program is working perfectly and all i need is  HOW to display images dynamically on the streamed PDF file.
    Can you help me with this??

    Thanks

    Prashanth K

  • User profile image
    MrSwifty1

    Hi

    Can anyone tell me how and with what software I can create a template PDF file with form fields?
    Acrobat reader no longer allows you to do it and I cant get my hands on the older versions.
    Is there a freeware app out there that can help me do this?

    I'm creating the invoicing portion of an internal site for my company and I need a template invoice which I can just populate with client details and the work to be billed.

    Thanks,
    Neil

  • User profile image
    Jack Dong .NET

    Filth said:

    Hi,

    I've just starting using iTextSharp in a code behind page, but when I run it, it just shows a empty pdf.

    I was wondering if anyone could see anything crazy that I have or haven't done?

    The code in my page_load event is:

    MemoryStream m = new MemoryStream();

    Document document = new Document(PageSize.A4.Rotate(), 10, 10, 10, 10);

    try

    {

    Response.ContentType = "application/pdf";

    PdfWriter.GetInstance(document, m);

    document.Open();

    document.Add(new Paragraph(DateTime.Now.ToString()));

    document.Add(new Paragraph("This is another test"));

    document.Add(new Paragraph("Yet another test"));

    }

    catch (DocumentException ex)

    {

    Console.Error.WriteLine(ex.StackTrace);

    Console.Error.WriteLine(ex.Message);

    }

    // step 5: Close document

    document.Close();

    // step 6: Write pdf bytes to outputstream

    Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length);

    Response.OutputStream.Flush();

    Response.OutputStream.Close();

    hi,everyone
    I want draw Bezier Lines for PDF with iTextsharp.

    But i did not konw how to do it.

    whether some friends konw that, pls tell me.

    my email:
         dlonghow@163.com

    or msn:
         dlonghow@hotmail.com


    Thank you everyone.

  • User profile image
    elrocael

    sbc said:
    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")

    Spanish

     

    Amigo Muchas Gracias el Código me sirvió para leer unos campos de un archivo pdf que tengo, necesitaba extraer los valores de esos campos para carcularlos y luego ingresarlos en otro archivo pdf, de verdad Muchas Gracias, le hice las siguientes modinicaciones.

     

     

    Imports

    Imports

    Imports

    Imports

    Imports

    Imports

    Imports

    Imports

    Imports

     

    Public

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.ClickDim m As MemoryStream = New MemoryStream()'

    which document to open Dim file As String = ("c:\prueba.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 name1 As String = outStamper.AcroFields.GetField("Texto2") 'este es le nombre del campo de texto pdf

    TextBox1.Text = TextBox1.Text & name1

     

    End

    End Sub Class

     

     

     

    System System.IO iTextSharp.text iTextSharp.text.pdf System.Data System.Text System.Drawing System.ComponentModel System.Collections Class Form1

Conversation locked

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