首先引入的依賴
<!-- poi庫(kù) -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
<!-- Apache PDFBox庫(kù)(用于處理PDF文件) -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.27</version>
</dependency>
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.9.0</version>
</dependency>
接下面的是template.docx文檔,參數(shù)是以{{paramName}}格式的,為什么要以這種格式,是因?yàn)橄旅娴姆椒?在替換參數(shù)的時(shí)候需要
XWPFTemplate template = XWPFTemplate.compile( "C:\\Users\\Administrator\\Desktop\\template.docx").render(jsonObject);
但是從數(shù)據(jù)庫(kù)獲取的參數(shù)跟模板中的參數(shù)一一對(duì)應(yīng)上即可,格式如下(我是json形式展示的):
{
?? ?"countQuota": "1",
?? ?"noEmission": "1",
?? ?"greenConsume": "1",
?? ?"pollutCharge": "1",
?? ?"emissionPermit": "C:\\Users\\Administrator\\Desktop\\",
?? ?"capitalOutlay": "1",
?? ?"carbonTarget": "1",
?? ?"zeroEmissionPower": "",
?? ?"kgce": "",
?? ?"productStandard": "",
?? ?"totalConsume": "",
?? ?"carbonEmission": "",
?? ?"consumePer": "",
?? ?"fileNames": "1.png,2.jpg,3.pdf",
?? ?"directEmission": "",
?? ?"indirectEmission": "1",
?? ?"partiEmission": "1"
}
template.docx文檔
大體上長(zhǎng)這樣
?這里主要給圖片中4.15排污許可證那里插入文件
具體代碼如下:
package com.example.threaddemo.test;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.deepoove.poi.XWPFTemplate;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;
import java.util.Map;
public class WordTest3 {
public static void main(String[] args) throws Exception {
String str = "{\n" +
"\t\"countQuota\": \"1\",\n" +
"\t\"noEmission\": \"1\",\n" +
"\t\"greenConsume\": \"1\",\n" +
"\t\"pollutCharge\": \"1\",\n" +
"\t\"emissionPermit\": \"C:\\\\Users\\\\Administrator\\\\Desktop\\\\\",\n" +
"\t\"capitalOutlay\": \"1\",\n" +
"\t\"carbonTarget\": \"1\",\n" +
"\t\"zeroEmissionPower\": \"\",\n" +
"\t\"kgce\": \"\",\n" +
"\t\"productStandard\": \"\",\n" +
"\t\"totalConsume\": \"\",\n" +
"\t\"carbonEmission\": \"\",\n" +
"\t\"consumePer\": \"\",\n" +
"\t\"fileNames\": \"1.png,2.jpg,滴滴電子發(fā)票.pdf\",\n" +
"\t\"directEmission\": \"\",\n" +
"\t\"indirectEmission\": \"1\",\n" +
"\t\"partiEmission\": \"1\"\n" +
"}";
//str = str.replace("\n","");
//str.replace("}","\"}");
//str = str.replaceAll("\\\\667A", "667A");
System.out.println("str = " + str);
//Map<String, String> jsonObject = JSONObject.parseObject(str, Map.class);
JSONObject jsonObject = JSONObject.parseObject(str);
//.render(jsonObject) json,map或者實(shí)體類都是可以的,只要參數(shù)能對(duì)上就可以了
XWPFTemplate template = XWPFTemplate.compile( "C:\\Users\\Administrator\\Desktop\\generate-template.docx").render(jsonObject);
template.write(new FileOutputStream("C:\\Users\\Administrator\\Desktop\\1.docx"));
template.close();
if (StringUtils.isNotBlank(jsonObject.getString("emissionPermit"))) {//說明排污許可證上傳了
XWPFDocument document = new XWPFDocument(new FileInputStream("C:\\Users\\Administrator\\Desktop\\1.docx"));
// 獲取文檔中的表格列表
List<XWPFTable> tables = document.getTables();
String path_pre = jsonObject.getString("emissionPermit");
String fileNames = jsonObject.getString("fileNames");
// 遍歷表格
for (XWPFTable table : tables) {
// 遍歷表格的行
List<XWPFTableRow> rows = table.getRows();
for (XWPFTableRow row : rows) {
// 遍歷行的單元格
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
// 獲取單元格的文本內(nèi)容
String cellText = cell.getText();
if (cellText.contains(path_pre)) {
XWPFRun run = cell.getParagraphs().get(0).getRuns().get(0);
run.setText("", 0);//置空里面的參數(shù){{emissionPermit}}
for (String filename : fileNames.split(",")) {
String file_path = path_pre + filename;
System.out.println("file_path = " + file_path);
// 加載Word文檔
if (file_path.endsWith(".png")) {
int type = XWPFDocument.PICTURE_TYPE_PNG;
insertImage(file_path, type, run, filename);
}
if (file_path.endsWith(".jpg")) {
int type = XWPFDocument.PICTURE_TYPE_JPEG;
insertImage(file_path, type, run, filename);
}
if (file_path.endsWith(".pdf")) {
String newFilePath = file_path.replace(".pdf", ".png");
convertPdfToImage(file_path, newFilePath);
int type = XWPFDocument.PICTURE_TYPE_PNG;
insertImage(newFilePath, type, run, filename);
File newFile = new File(newFilePath);
newFile.delete();//把pdf生成的png圖片刪除
}
}
// 保存修改后的文檔
FileOutputStream outputStream1 = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\1.docx");
document.write(outputStream1);
outputStream1.close();
}
}
}
}
}
//jsonObject.remove("emissionPermit");
}
//將pdf轉(zhuǎn)為png
private static void convertPdfToImage(String pdfPath, String imagePath) throws IOException {
PDDocument document = PDDocument.load(new File(pdfPath));
PDFRenderer renderer = new PDFRenderer(document);
BufferedImage image = renderer.renderImage(0); // 渲染第一頁(yè)為圖像
ImageIO.write(image, "PNG", new File(imagePath));
document.close();
}
//將圖片插入到指定位置
private static void insertImage(String filePath, int type, XWPFRun run, String fileName) {
try (InputStream pngInputStream = new FileInputStream(filePath)) {
byte[] jpgBytes = IOUtils.toByteArray(pngInputStream);
run.addPicture(new ByteArrayInputStream(jpgBytes), type, fileName, Units.toEMU(300), Units.toEMU(200));
} catch (Exception e) {
//LOGGER.info("tcfd插入圖片異常,異常原因:",e.getMessage(),e);
throw new RuntimeException(e);
}
}
}
在網(wǎng)上找了半天也么有什么好的方式可以在指定的位置直接將pdf插入進(jìn)去,如果哪位大神有好的方式,可以留個(gè)言
如果在運(yùn)行的過程中有這個(gè)報(bào)錯(cuò):java.lang.NoClassDefFoundError: org/apache/fontbox/cmap/CMapParser文章來源:http://www.zghlxwxcb.cn/news/detail-558117.html
請(qǐng)加下下面的依賴文章來源地址http://www.zghlxwxcb.cn/news/detail-558117.html
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>fontbox</artifactId>
<version>2.0.27</version>
</dependency>
到了這里,關(guān)于Java將獲取的參數(shù),圖片以及pdf文件放入到word文檔指定位置的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!