簡體   English   中英

實際使用 PDF Clown 裁剪 PDF

[英]Actually cropping a PDF with PDF Clown

我的目標實際上是用 PdfClown 裁剪一個 PDF 文件。 有很多工具/庫允許裁剪 PDF,更改 PDF 裁剪框。 這允許隱藏矩形區域之外的內容,但內容仍然存在,它可能通過 PDF 解析器訪問並且 PDF 大小不會改變。

相反,我需要的是創建一個僅包含矩形區域內內容的新頁面。

到目前為止,我已經嘗試掃描內容並有選擇地克隆它們。 但我還沒有成功。 關於使用 PdfClown 的任何建議?

我見過有人嘗試使用 PdfBox 從 PDF 頁面裁剪區域,但尚未成功。

有點晚了,但也許對某人有幫助; 我正在成功地做你所要求的 - 但與其他圖書館。 所需的庫:iText 4 或 5 和 Ghostscript

步驟 1 使用偽代碼

使用 iText,創建一個帶有空白文檔的 PDFWRITER 實例。 打開 PDFREADER 對象到要裁剪的原始文件。 導入頁面,從源獲取 PDFTemplate 對象,將其.boundingBox屬性設置為所需的裁剪框,將模板包裝到 iText Image 對象中,並將其粘貼到新頁面的絕對位置。

Dim reader As New PdfReader(sourcefile)
Dim doc As New Document()
Dim writer As PdfWriter = PdfWriter.GetInstance(doc, New System.IO.FileStream(outputfilename, System.IO.FileMode.Create))

//get the source page as an Imported Page
Dim page As PdfImportedPage = writer.GetImportedPage(reader, indexOfPageToGet) page

//create PDFTemplate Object at original size from source - see iText in Action book Page 91 for full details
Dim pdftemp As PdfTemplate = page.CreateTemplate(page.Width, page.Height) 
//paste the original page onto the template object, see iText documentation what those parameters do (scaling, mirroring)
pdftemp.AddTemplate(page, 1, 0, 0, 1, 0, 0)
//now the critical part - set .boundingBox property on the template. This makes all objects outside the rectangle invisible
pdftemp.boundingBox = {iText Rectangle Structure with new Cropbox}
//template not needed anymore
writer.ReleaseTemplate(pdftemp) 
//create an iText IMAGE object as wrapper to the template - with this img object absolute positionion on the final page is much easier
dim img as iTextSharp.Text.Image = Image.GetInstance(pdftemp)
// set img position
img.SetAbsolutePosition(x, y)
//set optional Rotation if needed
img.RotationDegrees = 0
//finally, this adds the actual content to the new document
doc.Add(img) 
//cleanup
doc.Close()
reader.Close()
writer.Close()

輸出文件將在視覺上看起來被裁剪。 但是對象仍然存在於 PDF 流中。 文件大小可能會保持很小的變化。

第 2 步:

使用 Ghostscript 和輸出設備 pdfwrite,結合正確的命令行參數,您可以重新處理步驟 1 中的 PDF。這將為您提供更小的 PDF。 有關參數,請參閱 Ghostscript 文檔https://www.ghostscript.com/doc/9.52/Use.htm此步驟實際上消除了邊界框之外的對象 - 您在 OP 中要求的要求,至少對於文件我處理的。

可選步驟 3:使用帶有 -g 選項的 MUTOOL,您可以清理未使用的外部參照對象。 您的原始 PDF 可能有很多外部參照,這會增加文件大小。 裁剪后,其中一些可能不再需要了。 https://mupdf.com/docs/manual-mutool-clean.html

PDF 格式是一件棘手的事情,通常我會同意@Tilman Hausherr ,我的建議可能不適用於所有文件並涵蓋“幾乎不可能”的情況,但它適用於我處理的所有情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM