开发者

Crop/resize a page after adding content?

I'm wondering if the dimensions of a page can be altered after content has been added to it?

I'm creating a PDF document in code using iTextSharp, and placing some content on a page. I'll only know the height of the content after drawing it, 开发者_JAVA技巧then I need to basically "crop" the page, so that it's only as tall as the content.

I know I can do this by writing the content to a pdfTemplate, then doing SetPageSize() and NewPage(), then adding the template to the new page. However, this document must only have 1 page. That's the catch - I can't set the size of page 1 after the fact, only subsequent pages, but the doc must only contain one page.

Unless there's a way of deleting page 1 after adding the properly-sized second page, I can't think of how to achieve this: A one-page PDF whose page size I have to change after having written content to it.


I ended up doing the following:

  1. Create document as a memorystream.
  2. Create a pdfTemplate, add content to it and remember how big the content is.
  3. Add a new (2nd) page, the same size as the content, and add template to it.
  4. Reseek to start of memorystream, open a PdfReader on it.
  5. Create a new PDF file with PdfCopy, copying the 2nd page from memory to the file.

After a day searching for a more direct method, this seemed the most expedient. Basically:

dim ms As New IO.MemoryStream
dim doc As New Document
dim pw As PdfWriter = PdfWriter.GetInstance(doc, ms)
doc.Open
Dim cb As PdfContentByte = pw.DirectContent
Dim tpl = cb.CreateTemplate(doc.PageSize.Width, doc.PageSize.Height)
... add content to template ...

' Add template to a new page of the right dimensions
doc.Add(New Paragraph(" ")) ' page 1 content required for NewPage to work
doc.SetPageSize(New Rectangle(width, height)) ' size of content we added
doc.NewPage()
cb.AddTemplate(tpl, 0, 0)
' Close our in-memory doc but leave stream open.
pw.CloseStream = False
pw.Close()
doc.Close()

' Now create actual file and write only second page of doc.
ms.Seek(0, IO.SeekOrigin.Begin) ' Go back to start of memorystream
Dim pr As New PdfReader(ms)
doc = New Document(pr.GetPageSizeWithRotation(2)) ' New doc, size of page 2
Dim copier As New PdfCopy(doc, New IO.FileStream(<filename>, IO.FileMode.Create))
doc.Open()
copier.AddPage(copier.GetImportedPage(pr, 2)) ' Add page 2 of our in-memory document.
copier.Close()
doc.Close()
pr.Close()

Now I have a PDF with a single page custom sized to the content which was added.
Hope it helps someone else!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜