Convert word to pdf (supports Linux system) and stamp the PDF at the specified location

1. Key points

Two methods, Method 1: Use documents4j to convert word to pdf, but it is not friendly to the Linux system. There are pitfalls and pitfalls. Don’t ask. The question is that I used documents4j from the beginning. As a result, I found that I could not convert pdf when I updated the version. Looking for information in the log, I found that Linux is not supported. If you want to support Linux but the process is cumbersome, you need to install offic components on Linux. If you don't mind the trouble, you can try to find information on how to install offic components. Method 2: Based on aspose-words, it is powerful and can be used perfectly on Linux. The disadvantage is that it is paid. If conditions permit, it is recommended to ignore the license.xml below and use the genuine version. I used method 2, the reference is as follows:

2. Method 2 (based on aspose-words)

1.jar download

First, you need the aspose-words-15.8.0-jdk16.jar package. An old man provided the resources.

Link: https://pan.baidu.com/s/13TIfBGFDgDJlxVonzUpgQQ Extraction code: sbkg

2.Put the jar into the local warehouse

<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>words</artifactId>
    <version>15.8.0</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.4.3</version>
</dependency>

mvn install:install-file -Dfile="E:\安装包\Java\aspose-words-15.8.0-jdk16.jar" -DgroupId=com.aspose -DartifactId=words -Dversion=15.8.0 -Dpackaging=jar

Note:

-Dfile is the local path where you downloaded the jar
-DgroupId is the groupId in dependency
-DartifactId is the artifactId in dependency
-Dversion is the version in dependency

3.Introduce license.xml

Create the license.xml file yourself and place it anywhere under resources

<License>
    <Data>
        <Products>
            <Product>Aspose.Total for Java</Product>
            <Product>Aspose.Words for Java</Product>
        </Products>
        <EditionType>Enterprise</EditionType>
        <SubscriptionExpiry>20991231</SubscriptionExpiry>
        <LicenseExpiry>20991231</LicenseExpiry>
        <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
    </Data>
    <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>
 

4.pdfUtil tool class

/** 
 * Generate pdf document 
 * @param Address The source file address is such as /root/example.doc 
 * @param Address1 The target file address is such as /root/example.pdf 
 */
public class PdfUtil { 
 public static void doc2pdf(String Address,String Address1) { 
    //Verify the License. If not verified, the converted pdf document will have a watermark 
    if (!getLicense()) { 
        return; 
    } 
    try { 
        //Create a new one Blank pdf document 
        long old = System.currentTimeMillis(); 
        File file = new File(Address1); 
        FileOutputStream os = new FileOutputStream(file); 
        //Address is the word document to be converted 
        Document doc = new Document(Address); 
        / / Fully supports DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF mutual conversion 
        doc.save(os, SaveFormat.PDF); 
        long now = System.currentTimeMillis(); 
        //Conversion time
        System.out.println("Total time spent: " + ((now - old) / 1000.0) + "seconds"); 
    } catch (Exception e) { 
        e.printStackTrace(); 
    } 
}

}

5. After converting the pdf, stamp the pdf with a table with 3 rows and 1 column, as shown below:

 

PdfUtil.doc2pdf(file, pdf); 

    PDDocument document = PDDocument.load(new File(pdf)); 
    // Get the first page 
    of PDPage firstPage = document.getPage(0); 
    PDFont font = PDType0Font.load(document, new File (FILE_BASE_URL + File.separator + FILE_DEMO_URL + File.separator + "Fangzhengshu Song.TTF")); 

    // Get the page size 
    PDRectangle pageSize = firstPage.getMediaBox(); 
    float pageWidth = pageSize.getWidth(); 
    float pageHeight = pageSize .getHeight(); 

    // Create content stream 
    PDPageContentStream contentStream = new PDPageContentStream(document, firstPage, PDPageContentStream.AppendMode.APPEND, true, true); 

    // Set text font and size 
    contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12); 
    contentStream.setNonStrokingColor(0, 0, 255); 

    / / Set line color to blue
    contentStream.setStrokingColor(0, 0, 255); 
    // Draw the inner and outer wireframe 
    float startX = 80; // Starting X coordinate 
    float startY = pageHeight - 80; // Starting Y coordinate 
    float cellWidth = 100; // Cell Width 
    float cellHeight = 20; // Cell height 

    // Draw table seal 
    for (int i = 0; i < 3; i++) { 
        float x = startX; 
        float y = startY - (i * cellHeight); 
        contentStream.addRect( x, y, cellWidth, cellHeight); 
        contentStream.stroke(); 
        String text = ""; 
        // Add text 
        if (i == 0) { 
            text = " **** "; 
        }  
        if (i == 1) {
            text = "**** (" + filingDetails.getFilingYear() + ")" + filingDetails.getNum() + "number"; 
        if 
        (i == 2) { 
            text = " ***** "; 
        } 
        contentStream.beginText(); 
        contentStream.newLineAtOffset(x + 5, y + 5); 
        contentStream.setFont(font, 8); 
        contentStream.showText(new String(text.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8)); 
        contentStream.endText(); 
    } 
    contentStream.close(); 
    // Save the modified PDF file 
    document.save(pdf); 
    document.close(); 

    // Export pdf to 
    String pdfName = pdf.substring(file.lastIndexOf( "/") + 1);
    CommonUtils.setResponseHeader(response, pdfName); 
    InputStream is = Files.newInputStream(Paths.get(pdf)); 
    OutputStream os = new BufferedOutputStream(response.getOutputStream());
    //Create an array byte[] to store the file content 
    buff = new byte[1024]; 
    //The read content uses n to receive 
    int n; 
    //When the reading is not completed, continue reading and loop 
    while (( n = is.read(buff)) != -1) { 
        //Write all the byte array data into the output stream 
        os.write(buff, 0, n); 
    } 
    os.flush(); 
    os. close(); 
    is.close(); 

} catch (IOException e) { 
    e.printStackTrace(); 
}

Note:

Founder Shu Song.TTF can be replaced according to your own situation

Link: https://pan.baidu.com/s/1cW_T-ut0bJ91Lg1Lj11g4A?pwd=2333 
Extraction code: 2333

Completed, welcome to ask questions for discussion.

Guess you like

Origin blog.csdn.net/m0_58823014/article/details/132445215