简体   繁体   中英

Crop a piece of a PDF page and save it as a new PDF document using itextsharp or itext7?

I need to save a rectangular area of a PDF file to a new PDF file, preferably using iTextSharp or iText7. I have managed to split the page to equal-sized pages, which works fine, but now I need to take an area with a custom size and location and have that in a separate page - once this is done, I can easily extract the page and save it as a separate pdf.

The code I have so far:

        public void manipulatePdf(string src, string dest)
    {  
        PdfReader reader = new PdfReader(src);
        iTextSharp.text.Rectangle pagesize = reader.GetPageSizeWithRotation(1); 
        Document document = new Document(pagesize); 
        PdfWriter writer = PdfWriter.GetInstance(document, 
            new FileStream(dest, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)); 
        document.Open();  
        PdfContentByte content = writer.DirectContent; 
        PdfImportedPage page = writer.GetImportedPage(reader, 1); 
        float x, y;

        x = 0;// -pagesize.Width * (0 % 4);
        y = 0;// pagesize.Height * (0 / 4 - 3);
        content.AddTemplate(page, 2, 0, 0, 2, x, y);
        document.NewPage();

        document.Close(); 
    }

Posting a solution in iText 7.

We are going to create a new document with one page which will be an exact copy of the original page we want to take an area from, but with the crop box defined. The crop box will make sure that the content is cut to the area you want. Do note that in this case the rest of the content (in the invisible area) is not gone and is still present in the internal document structures, so this solution can be applied in case you don't have any sensitive information inside of your document that you want to cut out. If you do have such sensitive information, take a look atpdfSweep add-on.

PdfDocument source = new PdfDocument(new PdfReader("C:\\source.pdf"));
PdfDocument croppedSinglePageTarget = new PdfDocument(new PdfWriter("C:\\cropped.pdf"));
Rectangle area = new Rectangle(200, 400, 200, 200);
int pageToCopy = 1;
source.copyPagesTo(pageToCopy, pageToCopy, croppedSinglePageTarget);
croppedSinglePageTarget.getPage(1).setCropBox(area);
source.close();
croppedSinglePageTarget.close();

Original document: 原始文件

Cropped result (200x200): 裁剪结果

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM