2

Have a little method which goes to the database and retrieves a pdf document from a varbinary column and then adds data to it. I would like to add code so that if this document (company stationery ) is not found then a new blank document is created and returned. The method could either return a Byte[] or a Stream.

Problem is that the variable "bytes" in the else clause is null.

Any ideas what's wrong?

private Byte[] GetBasePDF(Int32 AttachmentID)
{
    Byte[] bytes = null;
    DataTable dt =  ServiceFactory
        .GetService().Attachments_Get(AttachmentID, null, null);

    if (dt != null && dt.Rows.Count > 0)
    {
        bytes = (Byte[])dt.Rows[0]["Data"];
    }
    else
    {
        // Create a new blank PDF document and return it as Byte[]
        ITST.Document doc = 
           new ITST.Document(ITST.PageSize.A4, 50f, 50f, 25f, 25f);
        MemoryStream ms = new MemoryStream();

        PdfCopy copy = new PdfCopy(doc, ms);
        ms.Position = 0;

        bytes = ms.ToArray();

    }

    return bytes;
}
Chris Haas
  • 53,986
  • 12
  • 141
  • 274
Dave
  • 313
  • 1
  • 7
  • 18

2 Answers2

4

You are trying to use PdfCopy but that's intended for existing documents, not new ones. You just need to create a "blank" document using PdfWriter and Document. iText won't let you create a 100% empty document but the code below essentially does that by just adding a space.

private static Byte[] CreateEmptyDocument() {
    using (var ms = new System.IO.MemoryStream()) {
        using (var doc = new Document()) {
            using (var writer = PdfWriter.GetInstance(doc, ms)) {
                doc.Open();
                doc.Add(new Paragraph(" "));
                doc.Close();
            }
        }
        return ms.ToArray();
    }
}
Chris Haas
  • 53,986
  • 12
  • 141
  • 274
  • Thanks, that works a treat although I did change the return statement to .GetBuffer(); – Dave Nov 18 '13 at 07:22
  • @Dave *I did change the return statement to .GetBuffer()* - Most likely this implies that you have the PDF plus some trailing trash bytes (which might or might not be 0) in the returned `Byte[]`. Not a good idea; while Acrobat Reader often opens such documents without crying out load, this is against the specifications and some programs may reject your PDFs. – mkl Nov 18 '13 at 11:55
1

I think you may need to use

bytes = ms.GetBuffer();

not

bytes = ms.ToArray();
michaelrp
  • 663
  • 4
  • 9
  • 1
    `GetBuffer` will almost always cause problems. See http://stackoverflow.com/a/8606734/231316 and http://stackoverflow.com/a/5119739/231316 – Chris Haas Nov 18 '13 at 02:05
  • Ahh, didn't see your comment about not using .GetBuffer until after I had responded. – Dave Nov 18 '13 at 07:24