Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

memorystream - iTextSharp - Create new document as Byte[]

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...