3

I am trying to create pdf with multiple pages using iTextSharp

Document document = new Document(PageSize.A4, 2, 2, 10, 10);
private PdfContentByte _pcb;

try
{
    PdfWriter writer = PdfWriter.GetInstance(document, output);
    document.Open();             
    document.NewPage();
    _pcb = writer.DirectContent;
    _pcb.BeginText();
    _pcb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, x, y, 0);
    _pcb.EndText();
    writer.Flush();
}
catch(e)
{

}
finally
{
    document.Close();
}

This is working fine for me. When I am trying to add a new page on the same document, it is replacing the existing written text with new page and no new page is getting added. Below is the code which is not working.

_pcb.EndText();
writer.Flush();
document.NewPage();
_pcb = writer.DirectContent;
_pcb.BeginText();
_pcb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, x, y, 0);
_pcb.EndText();
writer.Flush();
1
  • Here After flushing the First page text I am trying to add a new page to the document Commented Jul 3, 2012 at 9:10

3 Answers 3

9

Below is my attempt to clean-up and unify your code. Generally avoid try-catch until you actually have to, you'll often miss some very important errors. (For instance, you're not actually setting the font and size which is required but maybe you just omitted that code.) Also, unless you are writing a very large PDF there's really no reason to flush the buffers, leave that to the OS to do for you when necessary.

When I run the code below I get two pages with text on both pages, does it work for you? (Targeting iTextSharp 5.2.0.0)

        var output = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Output.pdf");
        var bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
        using (FileStream fs = new FileStream(output, FileMode.Create, FileAccess.Write, FileShare.None)) {
            using (Document doc = new Document(PageSize.A4, 2, 2, 10, 10)) {
                PdfContentByte _pcb;
                using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) {
                    //Open document for writing
                    doc.Open();
                    //Insert page
                    doc.NewPage();
                    //Alias to DirectContent
                    _pcb = writer.DirectContent;
                    //Set the font and size
                    _pcb.SetFontAndSize(bf, 12);
                    //Show some text
                    _pcb.BeginText();
                    _pcb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Page 1", 40, 600, 0);
                    _pcb.EndText();
                    //Insert a new page
                    doc.NewPage();
                    //Re-set font and size
                    _pcb.SetFontAndSize(bf, 12);
                    //Show more text on page 2
                    _pcb.BeginText();
                    _pcb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Page 2", 100, 400, 0);
                    _pcb.EndText();
                    doc.Close();
                }
            }
        }
Sign up to request clarification or add additional context in comments.

1 Comment

I got my issue. while using _pcb.BeginText() I was not using _pcb.EndText as well didnt set a font before writing some text..thanks..
5

Why do you use the DirectContent? If you just want to create a PDF from scratch, just add content to the Document.

try
{
    iTextSharp.text.Document doc = new iTextSharp.text.Document();
    PdfWriter.GetInstance(doc, new FileStream("HelloWorld.pdf", FileMode.Create));
    doc.Open();
    doc.Add(new Paragraph("Hello World!"));
    doc.NewPage();
    doc.Add(new Paragraph("Hello World on a new page!"));
}
catch (Exception ex)
{

}
finally 
{
    doc.Close();
}

3 Comments

Thanks Alexis..Here I am rendering text based on the coordinate locations. How to use PdfContentByte for the same and when should I flush the text? once finishing the document or for each page.
Please tell me is there any alternative to print text on coordinate based system.
Use ColumnText to place text at an absolute position. Have a look at this example. Even though being written Java, the adaptation to C# should be fairly easy.
0

Below Code is working

string str = "Page1Page1Page1Page1Page1Page1Page1Page1Page1Page1";
string str2 = "Page2Page2Page2Page2Page2Page2Page2Page2Page2Page2";
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
using (var htmlWorker = new HTMLWokExtend(pdfDoc))
{
    using (var sr = new StringReader(str))
    {
        htmlWorker.Parse(sr);
    }
}
pdfDoc.NewPage();
using (var htmlWorker = new HTMLWokExtend(pdfDoc))
{
    using (var sr = new StringReader(str2))
    {
      htmlWorker.Parse(sr);
    }
}
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;" +
                               "filename=Proforma_Invoice.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();

You can populate string from HTML body using below function

private string populatebody()
{
    string body="";
    using (StreamReader reader = new StreamReader(Server.MapPath("~/Dir/Page.html")))
    {
        body = reader.ReadToEnd();
    }
    body = body.Replace("{Content in htmlpage}", "Your Content");
    return body
}

And then return this body to string in upper code. You can manipulate with this code as per your requirement.

Below is HTMLWokExtend Class:

public class HTMLWokExtend : HTMLWorker
{
    LineSeparator line = new LineSeparator(1f, 90f, BaseColor.GRAY, Element.ALIGN_CENTER, -12);
    public HTMLWokExtend(IDocListener document) : base(document)
    {

    }
    public override void StartElement(string tag, IDictionary<string, string> str)
    {
        if (tag.Equals("hrline"))
            document.Add(new Chunk(line));
        else
            base.StartElement(tag, str);
    }
}

2 Comments

What is this HTMLWokExtend?
Thanks for asking. I forgot to share this class. one more thing you need to add itextsharp dll reference where required.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.