当前位置:网站首页>IText 7 generate PDF summary
IText 7 generate PDF summary
2022-07-06 12:52:00 【Demon Lord】
Preface : Generate pdf There are many ways , This article USES the itextpdf 7 Generate
1、 according to PDF The requirements of are divided into static data, dynamic data and special data
1). Static data is data fixed , So we use template to generate -----itextpdf + Adobe Acrobat DC Fill template generation
Adobe Acrobat DC You can download the green version online
(1). Pass the file first WPS Generate PDF file
(2). use Adobe Acrobat DC Open the file for Prepare the form
(3). Configure the form field of the corresponding field
(4). Incoming data for printing
2). Dynamic data is not fixed , Code generation is required ---itext 7API Official address of iText 7 7.1.5 API
(1). Add dependency
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>7.1.5</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>kernel</artifactId>
<version>7.1.5</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>io</artifactId>
<version>7.1.5</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>layout</artifactId>
<version>7.1.5</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>forms</artifactId>
<version>7.1.5</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>pdfa</artifactId>
<version>7.1.5</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>sign</artifactId>
<version>7.1.5</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>barcodes</artifactId>
<version>7.1.5</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>hyph</artifactId>
<version>7.1.5</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>font-asian</artifactId>
<version>7.1.5</version>
</dependency>Attached at last is the first universal printing template I have written
Util Tool class
/**
* @author f
* @date 2021/9/28 16:56
*/
public class PrintUtil {
/**
* Chinese Fonts
*
* @return
* @throws IOException
*/
public static PdfFont typeface() throws IOException {
return PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H", true);
}
/**
* Template data
*
* @param map formFields
*/
public static void templateData(Map<String, String> map, Map<String, PdfFormField> formFields) throws IOException {
for (Map.Entry<String, String> entry : map.entrySet()) {
PdfFormField agreementId = formFields.get(entry.getKey());
if (agreementId != null) {
agreementId.setFont(typeface()).setFontSize(14);
agreementId.setValue(String.valueOf(entry.getValue()));
}
}
}
/**
* Template data set
*
* @param list formFields
*/
public static void templateDatas(List<Map<String, String>> list, Map<String, PdfFormField> formFields) throws IOException {
int i = 0;
for (Map<String, String> map : list) {
i++;
for (Map.Entry<String, String> entry : map.entrySet()) {
PdfFormField agerrmentId = formFields.get(entry.getKey() + "_" + i);
if (agerrmentId != null) {
agerrmentId.setFont(typeface()).setFontSize(14);
agerrmentId.setValue(String.valueOf(entry.getValue()));
}
}
}
}
/**
* Need to translate fields Match the template configuration
*
* @param estimate formFields
*/
public static void estimate(Map<String, String> estimate, Map<String, PdfFormField> formFields) throws IOException {
for (Map.Entry<String, String> entry : estimate.entrySet()) {
PdfFormField agerrmentId1 = formFields.get(entry.getValue());
if (StringUtils.isNotBlank(entry.getValue()) && agerrmentId1 != null) {
agerrmentId1.setFont(typeface()).setFontSize(14);
agerrmentId1.setValue("√");
}
}
}
/**
* Form title
*
* @param header
* @throws IOException
*/
public static Paragraph header(String header) throws IOException {
return new Paragraph(header)
// Set the font
.setFont(typeface())
// Set font size
.setFontSize(20)
// Bold font
.setBold()
// Set horizontal center
.setTextAlignment(TextAlignment.CENTER)
// Row height
.setFixedLeading(80);
}
/**
* The form data
*
* @return
* @throws IOException
*/
public static Table table(List<Map<String, String>> map, Map<String, String> biaotou) throws IOException {
//4. Create a Table object
int size = biaotou.entrySet().size();
UnitValue[] percentArray = UnitValue.createPercentArray(size);
Table table = new Table(percentArray)
.setFont(typeface())
// Vertical center
.setVerticalAlignment(VerticalAlignment.MIDDLE)
// Horizontal center
.setTextAlignment(TextAlignment.CENTER)
.setFontSize(18)
// Automatic layout
.setAutoLayout()
// The dynamic list exceeds the width of the table Use fixed layout
// .setFixedLayout()
//100%
.useAllAvailableWidth();
// Header
for (Map.Entry<String, String> entry : biaotou.entrySet()) {
table.addCell(entry.getValue());
}
for (Map<String, String> map1 : map) {
for (Map.Entry<String, String> entry : map1.entrySet()) {
table.addCell(entry.getValue());
}
}
return table;
}
/**
* Return file stream
*
* @param newPDFPath
* @param response
* @throws IOException
*/
public static void file(String newPDFPath, HttpServletResponse response) throws IOException {
// Read the file under the path
File file = new File(newPDFPath);
// Read the file under the specified path
InputStream in = new FileInputStream(file);
response.setContentType("application/pdf");
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
// Create an array of file contents
byte[] buff = new byte[1024];
// The read content uses n To receive
int n;
// When not finished reading , Continue reading , loop
while ((n = in.read(buff)) != -1) {
// Write all the data of the byte array to the output stream
outputStream.write(buff, 0, n);
}
if ((n = in.read(buff)) == -1) {
// Force the data in the cache to be output
outputStream.flush();
// Shut off flow
outputStream.close();
in.close();
}
}
}Entity class
/**
* pdf Template view entity class
*
* @author f
* @since 2021-09-17
*/
@Data
@EqualsAndHashCode(callSuper = true)
@ApiModel(value = "PrintVO object ", description = "pdf Templates ")
public class PrintVO extends Print {
private static final long serialVersionUID = -5917961640607855978L;
@ApiModelProperty(value = " Template data ")
private Map<String, String> map;
@ApiModelProperty(value = " Template data set ")
private List<Map<String, String>> list;
@ApiModelProperty(value = " Special data ")
private Map<String, String> estimate;
@ApiModelProperty(value = " Table title ")
private String header;
@ApiModelProperty(value = " Form header ")
private Map<String, String> biaotou;
@ApiModelProperty(value = " The form data ")
private List<Map<String, String>> table;
@ApiModelProperty(value = " Table title 1")
private String header1;
@ApiModelProperty(value = " Form header ")
private Map<String, String> biaotou1;
@ApiModelProperty(value = " The form data ")
private List<Map<String, String>> table1;
}controller layer
/**
* Print
*/
@PostMapping("/template")
@ApiOperationSupport(order = 9)
@ApiOperation(value = " Print ", notes = "PDF Templates ")
public void template(@RequestBody PrintVO print, HttpServletResponse response, @RequestParam String id) {
printService.template(print, response, id);
}service layer
/**
* PDF Templates Service implementation class
*
* @author f
* @since 2021-09-17
*/
@Service
public class PrintServiceImpl extends ServiceImpl<PrintMapper, Print> implements IPrintService {
@Override
public void template(PrintVO print, HttpServletResponse response, String id) {
// Template path
Print print1 = new Print();
print1.setId(Long.valueOf(id));
Print detail = this.getOne(Condition.getQueryWrapper(print1));
String templatePath = detail.getFileName();
if (templatePath == null) {
throw new ServiceException(" Template does not exist ");
}
// New file path generated
String newPDFPath = "\\ Templates .pdf";
try {
PdfDocument pdfDoc = new PdfDocument(new PdfReader(templatePath), new PdfWriter(newPDFPath));
PdfAcroForm pdfAcroForm = PdfAcroForm.getAcroForm(pdfDoc, true);
Map<String, PdfFormField> formFields = pdfAcroForm.getFormFields();
// Template data
Map<String, String> map = print.getMap();
if (map != null) {
PrintUtil.templateData(map, formFields);
}
// Template data set
List<Map<String, String>> list = print.getList();
if (list != null) {
PrintUtil.templateDatas(list, formFields);
}
// Special judgment data
Map<String, String> estimate = print.getEstimate();
if (estimate != null) {
PrintUtil.estimate(estimate, formFields);
}
// Set the generated form to be non editable
pdfAcroForm.flattenFields();
// Generate form title
String ti = print.getHeader();
Document document = new Document(pdfDoc);
// Header data
Map<String, String> biaotou = print.getBiaotou();
// The form data
List<Map<String, String>> biaodan = print.getTable();
if (biaodan != null && biaotou != null) {
if (map != null || list != null || estimate != null) {
document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
}
Paragraph header = PrintUtil.header(ti);
document.add(header);
document.add(PrintUtil.table(biaodan, biaotou));
}
// The second dynamic form generation
String ti2 = print.getHeader();
if (ti2 != null) {
// Header data
Map<String, String> biaotou1 = print.getBiaotou1();
// The form data
List<Map<String, String>> biaodan1 = print.getTable1();
if (biaodan1 != null && biaotou1 != null) {
document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
Paragraph header = PrintUtil.header(ti2);
document.add(header);
document.add(PrintUtil.table(biaodan1, biaotou1));
}
}
// close
pdfDoc.close();
document.close();
PrintUtil.file(newPDFPath, response);
} catch (IOException e) {
e.printStackTrace();
}
}
}边栏推荐
- Halcon knowledge: gray_ Tophat transform and bottom cap transform
- [Leetcode15]三数之和
- How to add music playback function to Arduino project
- FairyGUI条子家族(滚动条,滑动条,进度条)
- [Offer29] 排序的循环链表
- MySQL error warning: a long semaphore wait
- 音乐播放(Toggle && PlayerPrefs)
- Matlab读取GNSS 观测值o文件代码示例
- Mysql database reports an error: row size too large (> 8126) Changing some columns to TEXT or BLOB or using ROW_ FORMAT=DY
- rtklib单点定位spp使用抗差估计遇到的问题及解决
猜你喜欢

NovAtel 板卡OEM617D配置步骤记录

地球围绕太阳转

Particle system for introduction to unity3d Foundation (attribute introduction + case production of flame particle system)

341. Flatten nested list iterator

MySQL shutdown is slow
![[算法] 剑指offer2 golang 面试题5:单词长度的最大乘积](/img/e0/cea31070d6365eb57013cdead4a175.png)
[算法] 剑指offer2 golang 面试题5:单词长度的最大乘积

Derivation of logistic regression theory

PR 2021 quick start tutorial, first understanding the Premiere Pro working interface

C programming exercise

(4) Data visualization of R language -- matrix chart, histogram, pie chart, scatter chart, linear regression and strip chart
随机推荐
[algorithm] sword finger offer2 golang interview question 1: integer division
Unity3d, Alibaba cloud server, platform configuration
Knowledge system of digital IT practitioners | software development methods -- agile
341. Flatten nested list iterator
3月15号 Go 1.18 正式版发布 了解最新特色以及使用方法
Unity3d makes the registration login interface and realizes the scene jump
【干货】提升RTK模糊度固定率的建议之周跳探测
Unity场景跳转及退出
Fairygui joystick
[offer78] merge multiple ordered linked lists
[Leetcode15]三数之和
Unity3D摄像机,键盘控制前后左右上下移动,鼠标控制旋转、放缩
FairyGUI簡單背包的制作
编辑距离(多源BFS)
(课设第一套)1-5 317号子任务 (100 分)(Dijkstra:重边自环)
wsl常用命令
There is no red exclamation mark after SVN update
Force buckle 1189 Maximum number of "balloons"
FairyGUI复选框与进度条的组合使用
Particle system for introduction to unity3d Foundation (attribute introduction + case production of flame particle system)