iTextSharp - Create new document as Byte[]

两盒软妹~` 提交于 2019-11-30 09:40:07

问题


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

回答1:


I think you may need to use

bytes = ms.GetBuffer();

not

bytes = ms.ToArray();



回答2:


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


来源:https://stackoverflow.com/questions/20031982/itextsharp-create-new-document-as-byte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!