itextsharp trimming pdf document's pages

前端 未结 3 1198
梦如初夏
梦如初夏 2020-12-17 22:05

I have a pdf document that has form fields that I\'m filling out programatically with c#. Depending on three conditions, I need to trim (delete) some of the pages from that

3条回答
  •  半阙折子戏
    2020-12-17 22:33

    Use PdfReader.SelectPages() combined with PdfStamper. The code below uses iTextSharp 5.5.1.

    public void SelectPages(string inputPdf, string pageSelection, string outputPdf)
    {
        using (PdfReader reader = new PdfReader(inputPdf))
        {
            reader.SelectPages(pageSelection);
    
            using (PdfStamper stamper = new PdfStamper(reader, File.Create(outputPdf)))
            {
                stamper.Close();
            }
        }
    }
    

    Then you call this method with the correct page selection for each condition.

    Condition 1:

    SelectPages(inputPdf, "1-4", outputPdf);
    

    Condition 2:

    SelectPages(inputPdf, "1-4,6", outputPdf);
    

    or

    SelectPages(inputPdf, "1-6,!5", outputPdf);
    

    Condition 3:

    SelectPages(inputPdf, "1-5", outputPdf);
    

    Here's the comment from the iTextSharp source code on what makes up a page selection. This is in the SequenceList class which is used to process a page selection:

    /**
    * This class expands a string into a list of numbers. The main use is to select a
    * range of pages.
    * 

    * The general systax is:
    * [!][o][odd][e][even]start-end *

    * You can have multiple ranges separated by commas ','. The '!' modifier removes the * range from what is already selected. The range changes are incremental, that is, * numbers are added or deleted as the range appears. The start or the end, but not both, can be ommited. */

提交回复
热议问题