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

JAVA生成pdf文件的實操教程

 更新時間:2022年11月12日 10:00:05   作者:瘋狂java杰尼龜  
PDF是可移植文檔格式,是一種電子文件格式,具有許多其他電子文檔格式無法相比的優(yōu)點,下面這篇文章主要給大家介紹了關(guān)于JAVA生成pdf文件的相關(guān)資料,文中通過圖文介紹的非常詳細,需要的朋友可以參考下

一、簡介

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

二、實操

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

Edit Configurations

三、原理解析

從這幾點深入剖析和總結(jié)這個小項目:

1.是什么?

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

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

freemarker,F(xiàn)reeMarker是模板引擎,一個Java類庫。
itextpdf,iText是一種生成PDF報表的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">標題</h1>
    <h4 class="title">副標題</h4>
    <span>當前時間: ${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存儲到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)建一個標準的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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 基于JavaMail的Java郵件發(fā)送

    基于JavaMail的Java郵件發(fā)送

    電子郵件的應用非常廣泛,例如在某網(wǎng)站注冊了一個賬戶,自動發(fā)送一封歡迎郵件,通過郵件找回密碼,自動批量發(fā)送活動信息等。本文將簡單介紹如何通過 Java 代碼來創(chuàng)建電子郵件,并連接郵件服務器發(fā)送郵件
    2021-10-10
  • Java網(wǎng)絡編程基礎(chǔ)篇之單向通信

    Java網(wǎng)絡編程基礎(chǔ)篇之單向通信

    這篇文章主要介紹了Java網(wǎng)絡編程里通過套接字實現(xiàn)單向通信的方法及相關(guān)實例,屬于網(wǎng)絡編程入門程序,雖然簡單,但具有一定參考價值,需要的朋友可以參考下。
    2017-09-09
  • SpringBoot如何實現(xiàn)word文檔轉(zhuǎn)pdf

    SpringBoot如何實現(xiàn)word文檔轉(zhuǎn)pdf

    這篇文章主要介紹了SpringBoot如何實現(xiàn)word文檔轉(zhuǎn)pdf,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • JVM類加載器之ClassLoader的使用詳解

    JVM類加載器之ClassLoader的使用詳解

    類加載器負責讀取Java字節(jié)代碼,并轉(zhuǎn)換成java.lang.Class類的一個實例的代碼模塊。本文主要和大家聊聊JVM類加載器ClassLoader的使用,需要的可以了解一下
    2022-10-10
  • Springboot中的@ComponentScan注解使用解析

    Springboot中的@ComponentScan注解使用解析

    這篇文章主要介紹了Springboot中的@ComponentScan注解使用解析,@ComponentScan用于類或接口上主要是指定掃描路徑,spring會把指定路徑下帶有指定注解的類注冊到IOC容器中,需要的朋友可以參考下
    2024-01-01
  • Java設計模式之策略模式

    Java設計模式之策略模式

    這篇文章介紹了Java設計模式之策略模式,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-10-10
  • 詳解Spring框架入門

    詳解Spring框架入門

    這篇文章主要介紹了詳解Spring框架入門,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-04-04
  • Java服務端如何解決跨域問題?CORS請求頭方式

    Java服務端如何解決跨域問題?CORS請求頭方式

    這篇文章主要介紹了Java服務端如何解決跨域問題?CORS請求頭方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • Springboot3整合Mybatis3的完整步驟記錄

    Springboot3整合Mybatis3的完整步驟記錄

    這篇文章主要給大家介紹了關(guān)于Springboot3整合Mybatis3的完整步驟,Spring Boot和MyBatis分別是兩個功能強大的框架,它們的協(xié)同使用可以極大地簡化數(shù)據(jù)訪問層的開發(fā),提高整體的開發(fā)效率,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2024-01-01
  • Java連接并操作Sedna XML數(shù)據(jù)庫的方法

    Java連接并操作Sedna XML數(shù)據(jù)庫的方法

    這篇文章主要介紹了Java連接并操作Sedna XML數(shù)據(jù)庫的方法,較為詳細的說明了Sedna XML數(shù)據(jù)庫的原理與功能,并給出了基于java操作Sedna XML數(shù)據(jù)庫的方法,需要的朋友可以參考下
    2015-06-06

最新評論