0

I am in the process of updating some PDF editing tools from iTextSharp to iText7.

In iTextSharp there was a method in the pdfStamper class: pdfStamper.ReplacePage(). However, the pdfStamper class has been removed in iText7 and I am having trouble replicating the same functionality.

Say I have document X that needs page 4 replaced with page 1 of document Y but I want the result to be save to a new document Z.

So far I have 3 lines that use the CopyPageTo method. However any PDF document that gets created is only 1kb in size and corrupted.

Anyone have experience with the newer iText7 and the CopyPageTo method?

        NewPagesReader = New PdfReader(strNewPageDocPath)
        docNewPages = New PdfDocument(NewPagesReader)
        OriginalDocReader = New PdfReader(strOrigPageDocPath)
        docOringal = New PdfDocument(OriginalDocReader)

        Dim docNew As PdfDocument
        Dim NewPDFWriter As New PdfWriter(saver.FileName)
        docNew = New PdfDocument(NewPDFWriter)

        docOringal.CopyPagesTo(1, 3, docNew)
        docNewPages.CopyPagesTo(1, 1, docNew)
        docOringal.CopyPagesTo(5, 6, docNew)


        ToWriter.Close()
        docNew.Close()
Matt Bartlett
  • 348
  • 1
  • 3
  • 21
  • 1
    Which version of iText 7 are you using? Your code looks correct and with the latest version, 7.1.11, it works as expected in my tests. I have to remove `ToWriter.Close()` from your code sample. Make sure you're not overwriting or corrupting your output document with that line. – rhens May 07 '20 at 14:43
  • Hi rhens. I think it was that I was closing the writer before the document as I just tried removing that line and it worked fine. The Writer must be used in part of the PDFDocument close method to save it correctly. – Matt Bartlett May 07 '20 at 15:31

1 Answers1

0

Your code looks fine. Instead of copying all the pages to a new document, you can also delete and insert a page:

NewPagesReader = New PdfReader(strNewPageDocPath)
docNewPages = New PdfDocument(NewPagesReader)
OriginalDocReader = New PdfReader(strOrigPageDocPath)
Dim NewPDFWriter As New PdfWriter(saver.FileName)
docOringal = New PdfDocument(OriginalDocReader, NewPDFWriter)

docOringal.RemovePage(4)
docNewPages.CopyPagesTo(1, 1, docOringal, 4)

docOringal.Close()
rhens
  • 4,791
  • 3
  • 22
  • 38