java pdf文档生成

解决问题:生成pdf文件,linux系统环境和windows环境

文章入门级别:解决linux环境和windows环境字体问题,以及初步pdf生成

字体文件处理:

取C盘字体文件放到linux服务器,同时需要使字体文件生效(具体路径可依据实际情况建文件夹来处理)

命令:   fc-cache    /usr/share/fonts

宋体文件
C:\\Windows\\Fonts\\simsun.ttc

代码程序中windows环境写windows磁盘方法,linux写linux磁盘写法

/usr/share/fonts/simsun.ttc

工程结构

maven依赖

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>pdfdemo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <start-class>com.unique.PdfApplication</start-class>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.xhtmlrenderer</groupId>
            <artifactId>flying-saucer-pdf</artifactId>
            <version>9.1.22</version>
            <exclusions>
                <exclusion>
                    <artifactId>bcmail-jdk14</artifactId>
                    <groupId>org.bouncycastle</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>bcprov-jdk14</artifactId>
                    <groupId>org.bouncycastle</groupId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>3.0.12.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>yu</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.0.1.RELEASE</version>
                <configuration>
                    <mainClass>${start-class}</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

 

maven依赖

<dependency>
    <groupId>org.xhtmlrenderer</groupId>
    <artifactId>flying-saucer-pdf</artifactId>
    <version>9.1.22</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf -->
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>3.0.12.RELEASE</version>
</dependency>

核心代码

    public void generatePdf(String Prefix, String Suffix, String template_name, Map<String, Object> variablesMap, String file_path) {
        try {
            TemplateEngine templateEngine = new TemplateEngine();
            ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
            templateResolver.setTemplateMode(TemplateMode.HTML);
            templateResolver.setPrefix(Prefix);
            templateResolver.setSuffix(Suffix);
            templateResolver.setCharacterEncoding("UTF-8");
            templateEngine.setTemplateResolver(templateResolver);
            Context context = new Context();
            context.setVariables(variablesMap);
            String ht = templateEngine.process(template_name, context);
            ITextRenderer iTextRenderer = new ITextRenderer();
            ITextFontResolver fontResolver = iTextRenderer.getFontResolver();
            /**
             * linux 环境下 将字符集放到指定目录中
             * 例如/usr/fonts/simsun.ttc
             */
            fontResolver.addFont("C:\\Windows\\Fonts\\simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            iTextRenderer.setDocumentFromString(ht);
            iTextRenderer.layout();
            File file = new File(file_path);
            iTextRenderer.createPDF(new FileOutputStream(file));
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

模板文件,模板文件需要添加字体样式:style="font-family: SimSun;"

<!DOCTYPE html>
<html lang="en">
<body style="font-family: SimSun;">
<h1 style="text-align: center;">菜单价钱</h1>
<br/>
<b>
    <div style="text-align: left;"> 甲方:<span th:text="${user_name}"></span></div>
</b>
<br/>
<table style="font-size: 12px;border-collapse: collapse;" cellpadding="0" cellspacing="0" border="1px solid black">
    <tr>
        <td style="width: 36px;">序号</td>
        <td>物品分类</td>
        <td style="width: 176px;">寄送分类</td>
        <td style="width: 200px;">寄送条件</td>
    </tr>
</table>

</body>
</html>

具体代码

import com.lowagie.text.pdf.BaseFont;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * description: pdf linux windows初步生成测试
 */
@RestController
@Slf4j
public class PdfController {


    @RequestMapping(value = "getPdf")
    public String getPdf() throws Exception{
        log.info("当前打印信息:getPdf");
        Map<String, Object> map = new HashMap<>();
        map.put("user_name", "蜂房公司产品有限责任公司");
        TemplateEngine templateEngine = new TemplateEngine();
        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setPrefix("templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setCharacterEncoding("UTF-8");
        templateEngine.setTemplateResolver(templateResolver);
        Context context = new Context();
        context.setVariables(map);
        String ht = templateEngine.process("ht", context);
        ITextRenderer iTextRenderer = new ITextRenderer();
        ITextFontResolver fontResolver = iTextRenderer.getFontResolver();
        /**
         * linux写具体的文件路径 /usr/share/fonts/simsun.ttc
         */
        fontResolver.addFont("C:\\Windows\\Fonts\\simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        iTextRenderer.setDocumentFromString(ht);
        iTextRenderer.layout();
        /**
         * 写linux的磁盘路径
         */
        File file = new File("D:\\data\\pdf\\0809.pdf");
        try (FileOutputStream fileOutputStream = new FileOutputStream(file);) {
            iTextRenderer.createPDF(fileOutputStream);
            iTextRenderer.finishPDF();
        } catch (Exception e) {
            log.error("发生异常:{}", e.getMessage());
        }
        return "success";
    }
}

 

application.propertis

server.port=9002

启动,javar -jar +具体路径:javar -jar        yu.jar

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值