0

I spend a lot of time tweaking tables for a PDF I am putting together, so rather than wait until the whole report is finished, download it, open it, scroll down to relevant section... I put together the following debug function:

        public static void PreviewItextObject(PdfPTable table, PageStyle pageStyle)
        {
            using (PdfWriterChunk writerChunk = new PdfWriterChunk(pageStyle))
            {
                writerChunk.Document.NewPage();                    
                writerChunk.Document.Add(table);
                PreviewDocument(writerChunk.Document, writerChunk.memoryStream);
            }
        }
        public static void PreviewDocument(Document doc, MemoryStream ms)
        {
            doc.Close(); // have to close doc before embedding PDF
            var data = ms.ToArray();
            var filename = Path.GetTempFileName();
            filename += ".pdf";
            System.IO.File.WriteAllBytes(filename, data);
            System.Diagnostics.Process.Start(filename);
        }

where my PDFWriterChunk class looks like this:

        public PdfWriterChunk(PageStyle pageStyle)
        {
            memoryStream = new MemoryStream();
            var margin = GetMarginFromStyle(pageStyle);


            Document = new Document(pageStyle == PageStyle.LandScape ? PageSize.A4.Rotate() : PageSize.A4,
                margin.Left, margin.Right, margin.Top,
                margin.Bottom);
            Writer = PdfWriter.GetInstance(Document, memoryStream);
            Writer.SetPdfVersion(PDF_VERSION);
            Writer.CompressionLevel = PdfStream.BEST_COMPRESSION;
            Writer.SetFullCompression();

            PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, Document.PageSize.Height, 0.75f);

            Document.Open();

            PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, Writer);
            Writer.SetOpenAction(action);
      }

For myself to call from the immediate window. However what's really frustrating is when I do call it from the immediate window, nearly every first time I get the following exception, which takes a long time to throw:

An unhandled exception of type 'iTextSharp.text.DocumentException' occurred in itextsharp.dll Additional information: The operation has timed out

As soon as I ignore that error and run it again, it works!

So clearly something is causing a wait or lock of some kind on the document.add, that leads to a long wait that leads to the exception. But i'm not sure what, anyone have any ideas how to avoid it? it always happens in the add, the new page seems fine. I always call it at the point the code is about to add it to the real document, which works also fine on a normal run.

chrispepper1989
  • 2,100
  • 2
  • 23
  • 48

0 Answers0