Tech Off Post

Single Post Permalink

View Thread: ASP.NET and iTextSharp (free PDF Generator for .NET)
  • 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