0

I don't know how to solve this because the document seem close before the actual command even I put command to open it again. Please help.

This is my code. When I click the button it will do this and the error will occur at doc.close() line. It shown "Cannot access a closed file." Even I put doc.open() above.

private void run_Click(object sender, EventArgs e)
    {
        Document doc = new Document(PageSize.A4);

        using(FileStream op = new FileStream("text.pdf", FileMode.Create))
        {
            PdfWriter wri = PdfWriter.GetInstance(doc, op);
            Paragraph p = new Paragraph("test");
            doc.Open();
            doc.Add(p);
        }

        using (FileStream op = new FileStream("text.pdf", FileMode.Append, FileAccess.Write))
        {

            PdfWriter wri = PdfWriter.GetInstance(doc, op);
            Paragraph p = new Paragraph("test2");
            doc.Open();
            doc.Add(p);
            doc.Close();
        }

    }
tumsd923
  • 28
  • 6
  • Appending to a pdf file add you do makes no sense. – mkl Nov 15 '17 at 07:57
  • @mkl I did yesterday by create new Document instance and it was work, but I don't know if there are anyway to do it by not create new instance. – tumsd923 Nov 16 '17 at 02:39

1 Answers1

1

First of all, it is not a correct way to add some contents to an existing PDF by appending a PDF file. If you want to add contents to an existing PDF, please check ITextSharp insert text to an existing pdf.

However, if you just want it to work, you just need to create a new Document instance every time.

private void run_Click(object sender, EventArgs e)
{
    Document doc = new Document(PageSize.A4);

    using(FileStream op = new FileStream("text.pdf", FileMode.Create))
    {
        PdfWriter wri = PdfWriter.GetInstance(doc, op);
        Paragraph p = new Paragraph("test");
        doc.Open();
        doc.Add(p);
    }

    using (FileStream op = new FileStream("text.pdf", FileMode.Append, FileAccess.Write))
    {
        doc = new Document(PageSize.A4); // this is the fix
        PdfWriter wri = PdfWriter.GetInstance(doc, op);
        Paragraph p = new Paragraph("test2");
        doc.Open();
        doc.Add(p);
        doc.Close();
    }
}
Han Zhao
  • 1,932
  • 7
  • 10
  • You might want to stress that "if you just want it to work" was merely meant as "if you just want it to not throw an exception" because the result most likely still is not what the OP wanted to achieve with the code... – mkl Nov 16 '17 at 09:18