开发者

append image to EXISTING pdf using itextsharp

开发者 https://www.devze.com 2023-01-23 06:22 出处:网络
The following code is very good at putting a single page into a pdf. It does not work for subsequent pages.

The following code is very good at putting a single page into a pdf. It does not work for subsequent pages. If the stream is an existing pdf开发者_C百科 file the image is replaced. How do I get NewPage() to actually create a new page and add the image at the end.

        using (Stream ms = GetStream()) {

            Document doc = new Document(PageSize.A4);
            var writer = PdfWriter.GetInstance(doc, ms);

            doc.Open();
            if (!doc.NewPage())
                throw new InvalidOperationException("NewPage failed.");

            PDFImage jpg = PDFImage.GetInstance(image, ImageFormat.Jpeg);
            jpg.Alignment = Element.ALIGN_CENTER;
            jpg.ScaleToFit(PageSize.A4.Width, PageSize.A4.Height);
            doc.Add(jpg);

            doc.Close();
        }


Calling doc.NewPage() doesn't do anything when there's nothing on the current page. There are at least 3 options:

1) Add something invisible to the current page. An empty paragraph, some white space to the PdfContentByte, whatever. 2) Tell your PDF document "no, its really not empty, take my word": PdfDocument.PageEmpty =false; 3) Don't throw when NewPage returns false. That's perfectly acceptable under the circumstances.

I'd go with #3 personally.

0

精彩评论

暂无评论...
验证码 换一张
取 消