您好,登錄后才能下訂單哦!
這篇文章主要介紹“Java如何實現無損Word轉PDF”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“Java如何實現無損Word轉PDF”文章能幫助大家解決問題。
代碼實現主要依賴兩個第三方jar包,一個是pdfbox,一個是aspose-words。pdfbox包完全開源免費,aspose-words免費版生成有水印,且生成數量有限制。單純用pdfbox 實現word轉pdf的話,實現非常復雜,且樣式和原來樣式,保持一致的的比例很低。所以,我先用aspose-words生成了帶水印的pdf,再用pdfbox去除aspose-words生成的水印的,最終得到了一個無水印的pdf。
aspose-words 這個需要配置單獨的倉庫地址才能下載,不會配置的可以去官網直接下載jar引入項目代碼中。
<repositories> <repository> <id>AsposeJavaAPI</id> <name>Aspose Java API</name> <url>https://repository.aspose.com/repo/</url> </repository>
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox --> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>3.0.0-RC1</version> </dependency> <dependency> <groupId>com.github.jai-imageio</groupId> <artifactId>jai-imageio-jpeg2000</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>com.aspose</groupId> <artifactId>aspose-words</artifactId> <version>21.9</version> <type>pom</type> </dependency>
import com.aspose.words.Document; import com.aspose.words.SaveFormat; import org.apache.pdfbox.Loader; import org.apache.pdfbox.contentstream.operator.Operator; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.cos.COSString; import org.apache.pdfbox.pdfparser.PDFStreamParser; import org.apache.pdfbox.pdfwriter.ContentStreamWriter; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageTree; import org.apache.pdfbox.pdmodel.PDResources; import org.apache.pdfbox.pdmodel.common.PDStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class PDFHelper3 { public static void main(String[] args) throws IOException { doc2pdf("C:\\Users\\liuya\\Desktop\\word\\帆軟報表幫助文檔.docx"); } //替換pdf文本內容 public static void replaceText(PDPage page, String searchString, String replacement) throws IOException { PDFStreamParser parser = new PDFStreamParser(page); List<?> tokens = parser.parse(); for (int j = 0; j < tokens.size(); j++) { Object next = tokens.get(j); if (next instanceof Operator) { Operator op = (Operator) next; String pstring = ""; int prej = 0; if (op.getName().equals("Tj")) { COSString previous = (COSString) tokens.get(j - 1); String string = previous.getString(); string = string.replaceFirst(searchString, replacement); previous.setValue(string.getBytes()); } else if (op.getName().equals("TJ")) { COSArray previous = (COSArray) tokens.get(j - 1); for (int k = 0; k < previous.size(); k++) { Object arrElement = previous.getObject(k); if (arrElement instanceof COSString) { COSString cosString = (COSString) arrElement; String string = cosString.getString(); if (j == prej) { pstring += string; } else { prej = j; pstring = string; } } } if (searchString.equals(pstring.trim())) { COSString cosString2 = (COSString) previous.getObject(0); cosString2.setValue(replacement.getBytes()); int total = previous.size() - 1; for (int k = total; k > 0; k--) { previous.remove(k); } } } } } List<PDStream> contents = new ArrayList<>(); Iterator<PDStream> streams = page.getContentStreams(); while (streams.hasNext()) { PDStream updatedStream = streams.next(); OutputStream out = updatedStream.createOutputStream(COSName.FLATE_DECODE); ContentStreamWriter tokenWriter = new ContentStreamWriter(out); tokenWriter.writeTokens(tokens); contents.add(updatedStream); out.close(); } page.setContents(contents); } //移除圖片水印 public static void removeImage(PDPage page, String cosName) { PDResources resources = page.getResources(); COSDictionary dict1 = resources.getCOSObject(); resources.getXObjectNames().forEach(e -> { if (resources.isImageXObject(e)) { COSDictionary dict2 = dict1.getCOSDictionary(COSName.XOBJECT); if (e.getName().equals(cosName)) { dict2.removeItem(e); } } page.setResources(new PDResources(dict1)); }); } //移除文字水印 public static boolean removeWatermark(File file) { try { //通過文件名加載文檔 PDDocument document = Loader.loadPDF(file); PDPageTree pages = document.getPages(); Iterator<PDPage> iter = pages.iterator(); while (iter.hasNext()) { PDPage page = iter.next(); //去除文字水印 replaceText(page, "Evaluation Only. Created with Aspose.Words. Copyright 2003-2021 Aspose", ""); replaceText(page, "Pty Ltd.", ""); replaceText(page, "Created with an evaluation copy of Aspose.Words. To discover the full", ""); replaceText(page, "versions of our APIs please visit: https://products.aspose.com/words/", ""); replaceText(page, "This document was truncated here because it was created in the Evaluation", ""); //去除圖片水印 removeImage(page, "X1"); } document.removePage(document.getNumberOfPages() - 1); file.delete(); document.save(file); document.close(); return true; } catch (IOException ex) { ex.printStackTrace(); return false; } } //doc文件轉pdf(目前最大支持21頁) public static void doc2pdf(String wordPath) { long old = System.currentTimeMillis(); try { //新建一個pdf文檔 String pdfPath=wordPath.substring(0,wordPath.lastIndexOf("."))+".pdf"; File file = new File(pdfPath); FileOutputStream os = new FileOutputStream(file); //Address是將要被轉化的word文檔 Document doc = new Document(wordPath); //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互轉換 doc.save(os, SaveFormat.PDF); os.close(); //去除水印 removeWatermark(new File(pdfPath)); //轉化用時 long now = System.currentTimeMillis(); System.out.println("Word 轉 Pdf 共耗時:" + ((now - old) / 1000.0) + "秒"); } catch (Exception e) { System.out.println("Word 轉 Pdf 失敗..."); e.printStackTrace(); } } }
以一個帶文字和圖片,工21頁的doc文件為例,word轉pdf花費時長4.398秒
原word樣式
轉化后pdf效果圖
通過對比,word原來的樣式和轉換pdf文件后的樣式基本沒有變化。
關于“Java如何實現無損Word轉PDF”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。