0

I am using ITextSharp to convert HTML to PDF but i want the PDF to be generated of size 5cm width. I used the following code

var pgSize = new iTextSharp.text.Rectangle(2.05f, 2.05f);
Document doc = new Document(pgSize);

but it is just resizing the pdf and my data disappeared in the pdf or get hide. How can i align the data in the center in PDF or resize the pdf? Here is my code public void ConvertHTMLToPDF(string HTMLCode) {

        try
        {
            System.IO.StringWriter stringWrite = new StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

            StringReader reader = new StringReader(HTMLCode);

            var pgSize = new iTextSharp.text.Rectangle(2.05f, 2.05f);                
            Document doc = new Document(pgSize);
            HTMLWorker parser = new HTMLWorker(doc);

            PdfWriter.GetInstance(doc, new FileStream(Server.MapPath("~") + "/App_Data/HTMLToPDF.pdf",
            FileMode.Create));
            doc.Open();
            foreach (IElement element in HTMLWorker.ParseToList(
            new StringReader(HTMLCode), null))
            {

                doc.Add(element);
            }

            doc.Close();
            Response.End();
        }
        catch (Exception ex)
        {

        }
    }
Nitesh Kumar
  • 1,774
  • 4
  • 19
  • 26
Yash Katiyar
  • 31
  • 1
  • 1
  • 8
  • Possible duplicate of [Custom page size in iTextSharp in C#.NET](https://stackoverflow.com/questions/17079021/custom-page-size-in-itextsharp-in-c-net) – Nitesh Kumar Dec 29 '17 at 07:29
  • You shouldn't use `HTMLWorker`. See https://developers.itextpdf.com/content/itext-7-converting-html-pdf-pdfhtml and since when is 2.05 pt equal to 5cm? – Bruno Lowagie Dec 29 '17 at 11:00

1 Answers1

0

You are creating a PDF that measures 0.0723 cm by 0.0723 cm. That is much too small to add any content. If you want to create a PDF of 5 cm by 5 cm, you need to create your document like this:

var pgSize = new iTextSharp.text.Rectangle(141.732f, 141.732f);
Document doc = new Document(pgSize);

As for the alignment, that should be defined in the HTML, but you are using an old version of iText and you are using the deprecated HTMLWorker.

You should upgrade to iText 7 and pdfHTML as described here: Converting HTML to PDF using iText

Also: the size of the page can be defined in the @page-rule of the CSS. See Huge white space after header in PDF using Flying Saucer

Why would you make it difficult for yourself by using an old iText version, when the new version allows you to do this:

@page {
  size: 5cm 5cm;
}
Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165