Java實現無損Word轉PDF的示例代碼

前言

本來想寫word轉pdf和pdf轉word的代碼呢,沒想到word轉pdf就寫瞭很多很多行代碼才實現,為瞭方便大傢消化理解,先寫瞭word轉pdf方法實現作為一篇文章。

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>

Maven項目pom文件依賴

<!-- 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的示例代碼的文章就介紹到這瞭,更多相關Java無損Word轉PDF內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: