amesh
amesh

Reputation: 1319

Creating multiple page pdf using iTextSharp

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();

Upvotes: 3

Views: 35830

Answers (3)

Singh T
Singh T

Reputation: 161

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);
    }
}

Upvotes: 0

Chris Haas
Chris Haas

Reputation: 55417

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();
                }
            }
        }

Upvotes: 9

Alexis Pigeon
Alexis Pigeon

Reputation: 7512

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();
}

Upvotes: 5

Related Questions