翻譯|使用教程|編輯:張瑩心|2021-11-18 14:01:32.117|閱讀 671 次
概述:與 MS Word 不同,PDF 文檔中的文本幾乎無法修改,因為 PDF 不會自動重新排列頁面內容。Spire.PDF for Java提供的這個場景并沒有真正替換文檔中的現有文本,而是用一個白色矩形覆蓋舊文本并在其上繪制新文本。為避免替換后出現空格或重疊問題,請確保替換文本的長度與要替換的文本長度一樣長。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
Spire.PDF for Java 是一款專門對 PDF 文檔進行操作的 Java 類庫。該類庫的主要功能在于幫助開發人員在 Java 應用程序(J2SE和J2EE)中生成 PDF 文檔和操作現有 PDF 文檔,并且運行環境無需安裝 Adobe Acrobat。
與 MS Word 不同,PDF 文檔中的文本幾乎無法修改,因為 PDF 不會自動重新排列頁面內容。Spire.PDF for Java提供的這個場景并沒有真正替換文檔中的現有文本,而是用一個白色矩形覆蓋舊文本并在其上繪制新文本。為避免替換后出現空格或重疊問題,請確保替換文本的長度與要替換的文本長度一樣長。
查找和替換 PDF 中的文本
以下是在某個 PDF 頁面中查找所選文本的步驟,并用新字符串覆蓋它們。
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import com.spire.pdf.general.find.PdfTextFind; import com.spire.pdf.general.find.PdfTextFindCollection; import com.spire.pdf.graphics.*; import com.spire.pdf.graphics.fonts.PdfUsedFont; import com.spire.ms.System.Collections.Generic.List; import java.awt.*; import java.awt.geom.Rectangle2D; public class FindAndReplace { public static void main(String[] args) { //Create a PdfDocument object PdfDocument doc = new PdfDocument(); //Load a sample PDF document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf"); //Get the first page PdfPageBase page = doc.getPages().get(0); //Find the specific string from the page PdfTextFindCollection findResults = page.findText("Spire.PDF for Java", true, false); PdfTextFind[] findCollection = findResults.getFinds(); //Get the used fonts in the document PdfUsedFont[] usedFonts = doc.getUsedFonts(); //Create a PdfTrueTypeFont object based on a specific used font PdfTrueTypeFont pdfTrueTypeFont = new PdfTrueTypeFont(new Font(usedFonts[0].getName(), 0, (int) usedFonts[0].getSize())); //Define new text for replacing String newText = "Spire.PDF for .Net"; //Declare a List variable List rect; //Loop through the find collection for (int i = 0; i < findCollection.length; i++) { //Get the bounds of a specific find result rect = findCollection[i].getTextBounds(); //Draw a white rectangle to convert the old text page.getCanvas().drawRectangle(PdfBrushes.getWhite(), rect.get(0).getBounds2D()); //Draw new text at the position of the old text page.getCanvas().drawString(newText, pdfTrueTypeFont, PdfBrushes.getDarkBlue(), rect.get(0).getX(), rect.get(0).getMinY() - 1); } //Save to file doc.saveToFile("output/FindAndReplace.pdf"); } }
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn