欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JAVA生成pdf文件的實(shí)操指南

 更新時(shí)間:2022年10月13日 09:54:19   作者:瘋狂java杰尼龜  
最近項(xiàng)目需要實(shí)現(xiàn)PDF下載的功能,由于沒有這方面的經(jīng)驗(yàn),從網(wǎng)上花了很長時(shí)間才找到相關(guān)的資料,下面這篇文章主要給大家介紹了關(guān)于JAVA生成pdf文件的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下

一、簡介

PDF文件格式可以將文字、字型、格式、顏色及獨(dú)立于設(shè)備和分辨率的圖形圖像等封裝在一個(gè)文件中。本文實(shí)現(xiàn)將html頁面轉(zhuǎn)PDF。

二、實(shí)操

生成pdf文件成功,但是文字對(duì)不上。當(dāng)修改”GetHtmlContent“部分的編碼之后,再次執(zhí)行生成PDF文件即可完成正確的實(shí)現(xiàn)。

Edit Configurations

三、原理解析

從這幾點(diǎn)深入剖析和總結(jié)這個(gè)小項(xiàng)目:

1.是什么?

該項(xiàng)目實(shí)現(xiàn)了解析一個(gè)模板html文件,將其轉(zhuǎn)為pdf文件并輸出到相應(yīng)的目錄中。

1.1.關(guān)鍵技術(shù)

freemarker,F(xiàn)reeMarker是模板引擎,一個(gè)Java類庫。

itextpdf,iText是一種生成PDF報(bào)表的Java類庫,可以將Xml,Html文件轉(zhuǎn)化為PDF文件。

類 XMLWorkerHelper,(用于解析 XHTML/CSS 或 XML 流到 PDF 的幫助器類)。

2.怎么做?為什么?

相關(guān)依賴

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.2</version>
</dependency>
<dependency>
    <groupId>com.itextpdf.tool</groupId>
    <artifactId>xmlworker</artifactId>
    <version>5.5.13.2</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
    <version>2.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.28</version>
</dependency>

模板文件:generationpdf.html,所在目錄為src/main/resources/templates/generationpdf.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
    <style>
        body{font-family:SimSun;}
        .title{align-content: center;text-align: center;}
        .signature{float:right }
    </style>
</head>
<body>
<div>
    <h1 class="title">標(biāo)題</h1>
    <h4 class="title">副標(biāo)題</h4>
    <span>當(dāng)前時(shí)間: ${date_time} </span>
    <div class="signature">日期:${date}</div>
</div>
</body>
</html>

GetHtmlContent.java:獲取模板內(nèi)容

import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.*;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

public class GetHtmlContent {
    /**
     * 獲取模板內(nèi)容
     * @param templateDirectory 模板文件夾
     * @param templateName      模板文件名
     * @param paramMap          模板參數(shù)
     * @return
     * @throws Exception
     */
    public static String getTemplateContent(String templateDirectory, String templateName, Map<String, Object> paramMap) throws Exception {
        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);//不兼容配置
        try {
            configuration.setDirectoryForTemplateLoading(new File(templateDirectory));//加載模板
        } catch (Exception e) {
            System.out.println("-- exception --");
        }

        Writer out = new StringWriter();
        Template template = configuration.getTemplate(templateName,"UTF-8");//緩存
        template.process(paramMap, out);
        out.flush();
        out.close();
        return out.toString();
    }
    public static void main(String[] args) throws Exception {
        Map<String, Object> paramMap = new HashMap<>();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        paramMap.put("date_time", dateTimeFormatter.format(LocalDateTime.now()));
        paramMap.put("date", dateTimeFormatter.format(LocalDateTime.now()).substring(0, 10));
        ClassLoader classLoader = GetHtmlContent.class.getClassLoader();
        URL resource = classLoader.getResource("templates");
        String templateDirectory  =resource.toURI().getPath();

        String templateContent = GetHtmlContent.getTemplateContent(templateDirectory, "generationpdf.html", paramMap);
        System.out.println(templateContent);
    }
}

生成pdf文件,將date_time和date存儲(chǔ)到HashMap中,然后將數(shù)據(jù)輸出到pdf中

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;


public class GeneratePDF {
    /**
     * HTML 轉(zhuǎn) PDF
     * @param content html內(nèi)容
     * @param outPath           輸出pdf路徑
     * @return 是否創(chuàng)建成功
     */
    public static boolean html2Pdf(String content, String outPath) {
        try {
            Document document = new Document(); //創(chuàng)建一個(gè)標(biāo)準(zhǔn)的A4紙文檔
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outPath));//書寫器與ducument文檔關(guān)聯(lián)
            document.open();//打開文檔
            XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                    new ByteArrayInputStream(content.getBytes()), null, Charset.forName("UTF-8"));
            document.close();//關(guān)閉文檔
        } catch (Exception e) {
            System.out.println("生成模板內(nèi)容失敗"+e.fillInStackTrace());
            return false;
        }
        return true;
    }
    /**
     * HTML 轉(zhuǎn) PDF
     * @param content html內(nèi)容
     * @return PDF字節(jié)數(shù)組
     */
    public static byte[] html2Pdf(String content) {
        ByteArrayOutputStream outputStream = null;
        try {
            Document document = new Document();
            outputStream = new ByteArrayOutputStream();
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);
            document.open();
            XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                    new ByteArrayInputStream(content.getBytes()), null, Charset.forName("UTF-8"));
            document.close();
        } catch (Exception e) {
            System.out.println("------生成pdf失敗-------");
        }
        return outputStream.toByteArray();
    }
    public static void main(String[] args) throws Exception {
        Map<String, Object> paramMap = new HashMap<>();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        paramMap.put("date_time", dateTimeFormatter.format(LocalDateTime.now()));
        paramMap.put("date", dateTimeFormatter.format(LocalDateTime.now()).substring(0, 10));
        String outPath = "D:\\A.pdf";
        String templateDirectory = "src/main/resources/templates";
        String templateContent = GetHtmlContent.getTemplateContent(templateDirectory, "generationpdf.html", paramMap);
        GeneratePDF.html2Pdf(templateContent, outPath);
    }
}

3.參考

總結(jié) 

到此這篇關(guān)于利用JAVA生成pdf文件的文章就介紹到這了,更多相關(guān)JAVA生成pdf文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • JAVA 實(shí)現(xiàn)磁盤文件加解密操作的示例代碼

    JAVA 實(shí)現(xiàn)磁盤文件加解密操作的示例代碼

    這篇文章主要介紹了JAVA 實(shí)現(xiàn)磁盤文件加解密操作的示例代碼,幫助大家利用Java實(shí)現(xiàn)文件的加解密,感興趣的朋友可以了解下
    2020-09-09
  • 關(guān)于Dubbo初始問題

    關(guān)于Dubbo初始問題

    這篇文章主要介紹了關(guān)于Dubbo初始問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • java8 計(jì)算時(shí)間差的方法示例

    java8 計(jì)算時(shí)間差的方法示例

    這篇文章主要介紹了java8 計(jì)算時(shí)間差的方法示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-10-10
  • Spring mvc攔截器實(shí)現(xiàn)原理解析

    Spring mvc攔截器實(shí)現(xiàn)原理解析

    這篇文章主要介紹了Spring mvc攔截器實(shí)現(xiàn)原理解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-03-03
  • 詳解SpringBoot+Dubbo集成ELK實(shí)戰(zhàn)

    詳解SpringBoot+Dubbo集成ELK實(shí)戰(zhàn)

    這篇文章主要介紹了詳解SpringBoot+Dubbo集成ELK實(shí)戰(zhàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-10-10
  • IDEA中多行注釋及取消注釋的快捷鍵分享

    IDEA中多行注釋及取消注釋的快捷鍵分享

    這篇文章主要介紹了IDEA中多行注釋及取消注釋的快捷鍵分享,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2021-02-02
  • Java中數(shù)組復(fù)制的三種方式小結(jié)

    Java中數(shù)組復(fù)制的三種方式小結(jié)

    在Java中,數(shù)組復(fù)制是一種常見的操作,它允許開發(fā)人員在不修改原始數(shù)組的情況下創(chuàng)建一個(gè)新的數(shù)組,本文就來介紹三種方法,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-02-02
  • Java中的transient關(guān)鍵字解析

    Java中的transient關(guān)鍵字解析

    這篇文章主要介紹了Java中的 transient關(guān)鍵字解析,有時(shí)候我們的一些敏感信息比如密碼并不想序列化傳輸給對(duì)方,這個(gè)時(shí)候transient關(guān)鍵字就派上用場了,如果一個(gè)類的變量加上了transient關(guān)鍵字那么這個(gè)字段就不會(huì)被序列化,需要的朋友可以參考下
    2023-09-09
  • 從零構(gòu)建可視化jar包部署平臺(tái)JarManage教程

    從零構(gòu)建可視化jar包部署平臺(tái)JarManage教程

    這篇文章主要為大家介紹了從零構(gòu)建可視化jar包部署平臺(tái)JarManage教程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-05-05
  • 在netty中使用native傳輸協(xié)議的方法

    在netty中使用native傳輸協(xié)議的方法

    這篇文章主要介紹了在netty中使用native傳輸協(xié)議,這里我們只以Kqueue為例介紹了netty中native傳輸協(xié)議的使用,需要的朋友可以參考下
    2022-05-05

最新評(píng)論