tags:

views:

98

answers:

1

All of the examples I have seen so far using ITextSharp start from scratch and create a new document, add something to it and close it. What if I need to do multiple things to a PDF for example I want to add a paragraph and then add a line. For example if I run this simple console app in which I just create a PDF and add a paragraph and then close it everything runs fine.

class Program
{
    static void Main(string[] args)
    {
        Document pdfDoc = new Document();
        PdfWriter.GetInstance(pdfDoc, new FileStream("TestPDF.pdf", FileMode.Create));
        pdfDoc.Open();

        pdfDoc.Add(new Paragraph("Some Text added"));

        pdfDoc.Close();

        Console.WriteLine("The file was created.");
        Console.ReadLine();
    }
}

However if I need to do something else like draw a line like this

class Program
{
    static void Main(string[] args)
    {
        Document pdfDoc = new Document();
        PdfWriter.GetInstance(pdfDoc, new FileStream("TestPDF.pdf", FileMode.Create));
        pdfDoc.Open();

        pdfDoc.Add(new Paragraph("Some Text added"));

        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream("TestPDF.pdf", FileMode.OpenOrCreate));
        PdfContentByte cb = writer.DirectContent;
        cb.MoveTo(pdfDoc.PageSize.Width / 2, pdfDoc.PageSize.Height / 2);
        cb.LineTo(pdfDoc.PageSize.Width / 2, pdfDoc.PageSize.Height);
        cb.Stroke();
        writer.Close();

        pdfDoc.Close();

        Console.WriteLine("The file was created.");
        Console.ReadLine();
    }
}

I get an error when trying to open the file because it is already opened by pdfDoc. If I put the highlighted code after the pdfDoc.Close() I get an error saying "The Document is not opened" How do I switch from adding text to adding a line? Do I need to close the doc and then re-open it again with the PDFReader and modify it there or can I do it all at once?

+1  A: 

You're getting an error because you're trying to request a second instance of a PDFWriter when you already have one. The second PdfWriter.GetInstance(pdfDoc, new FileStream("TestPDF.pdf", FileMode.OpenOrCreate)); is not need. I made a small edit to your code and this now seems to work

Document pdfDoc = new Document();
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream("TestPDF.pdf", FileMode.OpenOrCreate));

pdfDoc.Open();
pdfDoc.Add(new Paragraph("Some Text added"));             
PdfContentByte cb = writer.DirectContent;
cb.MoveTo(pdfDoc.PageSize.Width / 2, pdfDoc.PageSize.Height / 2);
cb.LineTo(pdfDoc.PageSize.Width / 2, pdfDoc.PageSize.Height);
cb.Stroke();

pdfDoc.Close();

Console.WriteLine("The file was created.");
Console.ReadLine();
cecilphillip