java动态数据填充word转pdf

一、准备好模板

java动态数据填充word转pdf_第1张图片

二、构架项目

1、pom依赖、注意aspose-words依赖官网收费可能拉不下来,需要私聊

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.7.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.pdf</groupId>
	<artifactId>WordTransfromPdf</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>WordTransfromPdf</name>
	<description>WordTransfromPdf</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>com.itextpdf.tool</groupId>
			<artifactId>xmlworker</artifactId>
			<version>5.5.12</version>
		</dependency>
		<dependency>
			<groupId>org.bouncycastle</groupId>
			<artifactId>bcprov-jdk15on</artifactId>
			<version>1.69</version>
		</dependency>

		<dependency>
			<groupId>cn.hutool</groupId>
			<artifactId>hutool-all</artifactId>
			<version>5.7.22</version>
		</dependency>
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itextpdf</artifactId>
			<version>5.5.12</version>
		</dependency>
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itext-asian</artifactId>
			<version>5.2.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>4.1.2</version>
		</dependency>
		<dependency>
			<groupId>com.deepoove</groupId>
			<artifactId>poi-tl</artifactId>
			<version>1.10.4</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.8.0</version>
		</dependency>
		<dependency>
			<groupId>fakepath</groupId>
			<artifactId>aspose-words</artifactId>
			<version>20.4</version>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
		<dependency>
			<groupId>org.xhtmlrenderer</groupId>
			<artifactId>flying-saucer-pdf-itext5</artifactId>
			<version>9.1.20</version>
			<exclusions>
				<exclusion>
					<artifactId>itextpdf</artifactId>
					<groupId>com.itextpdf</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

2、构建Controller


/**
 * @author kc
 * @date Create in  2022/10/26
 */
@RestController
public class PdfController {
    @Autowired
    private PdfService  pdfService;
    @RequestMapping("/downloadPdf")
    @ResponseBody
    public void downloadPreapprovalPdf( HttpServletResponse response) throws UnsupportedEncodingException {
        String pdfFileName = LocalDateTimeUtil.format(LocalDateTimeUtil.now(), "yyyyMMddHHmmss");


        response.setContentType("application/pdf");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "content-type,x-requested-with,Authorization");
        response.setHeader("Access-Control-Expose-Headers", "Authorization,authenticated");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, OPTIONS");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Content-Disposition", "inline; filename= " + URLEncoder.encode(pdfFileName, "UTF-8")+".pdf");
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            outputStream.write(pdfService.generatePdf());

            outputStream.flush();
        }  catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

}

3、service层

注意项:

1. 指定fsLocalPath存放缓存文件夹
2. AsposeWordPDF中需要指定字体库,windows字体库:C:\Windows\Fonts linux: /usr/share/fonts
(如果没指定字体库,生成pdf会出现中文都是小方格)

public interface PdfService {

    byte[] generatePdf();

}


@Service
public class PdfServiceImpl implements  PdfService{
    @Override
    public byte[] generatePdf() {
        //缓存存放
        String  fsLocalPath="D:\\tmp";
        ClassPathResource resource = new ClassPathResource("wordTemplate/studentTemplate.docx");
        String docTemplateFile =  resource.getAbsolutePath();

        byte[] result = null;
        File tmpDocOutFile = null;
        File tmpPdfOutFile = null;

        try {
            tmpDocOutFile = File.createTempFile("SxzdPreapprovalReport", ".docx", new File(fsLocalPath));
            tmpPdfOutFile = File.createTempFile("SxzdPreapprovalReport", ".pdf", new File(fsLocalPath));

            LoopRowTableRenderPolicy loopRowPolicy = new LoopRowTableRenderPolicy();
             /**
             * 注意如果是集合元素一定要放入config
             */
            Configure config = Configure.builder()
                    .bind("subjectList", loopRowPolicy)
                    .useSpringEL(false)
                    .build();
            List<SubjectResult> subjectList=new ArrayList<SubjectResult>();
            subjectList.add(new SubjectResult("数学","tom",132));
            subjectList.add(new SubjectResult("语文","jack",150));

            Map<String, Object> data = new HashMap<>();

            data.put("title", "张三基本信息");
            data.put("subjectList", subjectList);
            data.put("user", new User("张三","123","高一一班"));



            XWPFTemplate template = XWPFTemplate.compile(resource.getStream(), config).render(
                    data);
            template.writeAndClose(new FileOutputStream(tmpDocOutFile));


            AsposeWordPDF.word2pdf(tmpDocOutFile.getAbsolutePath(), tmpPdfOutFile.getAbsolutePath());

            result = FileUtils.readFileToByteArray(tmpPdfOutFile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            FileUtils.deleteQuietly(tmpDocOutFile);
            FileUtils.deleteQuietly(tmpPdfOutFile);
        }

        return result;

    }
}


4、实体类

@Data
@AllArgsConstructor
public class User {

    private String userName;

    private String seqId;


    private String grade;
}
@Data
@AllArgsConstructor
//@NoArgsConstructor
public class SubjectResult {
    /**
     * 课程
     */
    private String  subject;
    /**
     * 老师
     */
    private String  teacher;
    /**
     * 分数
     */
    private int score;
}

三、测试

1、字体库指定不正确示例
java动态数据填充word转pdf_第2张图片

2、正确字体库示例

java动态数据填充word转pdf_第3张图片

四、git地址

https://github.com/kangchangchang/WordTransfromPdf.git

你可能感兴趣的:(工具轮子,java,word,pdf)