# java导出
| Thymeleaf动态渲染HTML然后导出PDF | 集导入、导出、加密Excel等多项功能的JAVA工具包MyExcel |
|---|---|
| Freemarker | 导出excel(含easyexcel) |
| EasyPoi到处excel |
# itextpdf导出pdf
# 引入相应的jar包
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf 导出pdf所需jar包 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian 导出pdf所需jar包 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 根据需要编写pdf模板
可以通过word编写模板后转成pdf,然后添加表单信息,注意每个表单项的名字,在编码中需要用到
注意添加的图片也是新增一个
文本域,
# 编写代码实现pdf导出
public static void main(String... args){
List<String> listStr = Arrays.asList("111","2522","3433","火大快救火","2019-06-29 11:11:11","think","2","不晓得");
//目标文件
String newPdfFile = "D:/JAVA_WORK/result.pdf";
try(FileOutputStream out = new FileOutputStream(newPdfFile);
ByteArrayOutputStream bos= new ByteArrayOutputStream()) {
//模板文件、文件路径根据项目来
String rootTemplatePath = Optional.ofNullable(ResourceUtils.getURL("classpath:").getPath())
.orElse("D:/JAVA_WORK/MyTestSpringBoot/src/main/resources/");
PdfReader reader = new PdfReader(rootTemplatePath+"templates/mongoAlarm.pdf");
PdfStamper stamper = new PdfStamper(reader,bos);
AcroFields form = stamper.getAcroFields();
// BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
// ArrayList<BaseFont> fontList = new ArrayList<>();
// fontList.add(bf);
// form.setSubstitutionFonts(fontList);
// int i = 0;
// for (String str : form.getFields().keySet()){
// form.setField(str, listStr.get(i++));
// }
for (int i = 0, length = listStr.size(); i < length; i++){
form.setField(i+1+"",listStr.get(i));
}
int pageNo = form.getFieldPositions("img").get(0).page;
Rectangle rectangle = form.getFieldPositions("img").get(0).position;
//精确定位图片位置,左+下
float x = rectangle.getLeft();
float y = rectangle.getBottom();
// float y = rectangle.getRight();
Image image = Image.getInstance(rootTemplatePath+"static/images/banner.jpg");
PdfContentByte pdfContentByte = stamper.getOverContent(pageNo);
//图片自适应
image.scaleToFit(rectangle.getWidth(),rectangle.getHeight());
image.setAbsolutePosition(x,y);
pdfContentByte.addImage(image);
//设置不可编辑
stamper.setFormFlattening(true);
stamper.close();
//至此已经按照模板生成完pdf文件<bos>,根据需求文件要输出到哪里,本例是直接在本地生成一个文件
Document document = new Document();
PdfCopy pdfCopy = new PdfCopy(document,out);
document.open();
PdfImportedPage pdfImportedPage = pdfCopy.getImportedPage(new PdfReader(bos.toByteArray()),1);
pdfCopy.addPage(pdfImportedPage);
document.close();
reader.close();
} catch (IOException | DocumentException e) {
e.printStackTrace();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* 保存图片到pdf文档
*
* @param fieldPosition 图片位置
* @param stamper 文档
*/
public static void saveImgToPdf(AcroFields.FieldPosition fieldPosition, PdfStamper stamper, String imgPath)
throws IOException, DocumentException {
int pageNo = fieldPosition.page;
Rectangle rectangle = fieldPosition.position;
//精确定位图片位置,左+下
float x = rectangle.getLeft();
float y = rectangle.getBottom();
byte[] imgByte;
if (imgPath.contains(SysConstants.HTTP_STR)) {
URL pathUrl = new URL(imgPath);
DataInputStream dataInputStream = new DataInputStream(pathUrl.openStream());
imgByte = IOUtils.toByteArray(dataInputStream);
} else {
File imgFile = ResourceUtils.getFile(imgPath);
FileInputStream fis = new FileInputStream(imgFile);
imgByte = IOUtils.toByteArray(fis);
}
Image image = Image.getInstance(imgByte, true);
PdfContentByte pdfContentByte = stamper.getOverContent(pageNo);
//图片自适应
image.scaleToFit(rectangle.getWidth(), rectangle.getHeight());
image.setAbsolutePosition(x, y);
pdfContentByte.addImage(image);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 问题
- 可以实现安全等要求
- 没法实现循环,编辑表单的时候,录入框的大小固定,无法自适应文本,只能文本自适应录入框
# poi实现word、excel、ppt转html
# word转html
package wordToHtml;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.w3c.dom.Document;
public class PoiWordToHtml {
public static void main(String[] args) throws Throwable {
final String path = "D:\\poi-test\\wordToHtml\\";
final String file = "人员选择系分.doc";
InputStream input = new FileInputStream(path + file);
HWPFDocument wordDocument = new HWPFDocument(input);
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
DocumentBuilderFactory.newInstance().newDocumentBuilder()
.newDocument());
wordToHtmlConverter.setPicturesManager(new PicturesManager() {
public String savePicture(byte[] content, PictureType pictureType,
String suggestedName, float widthInches, float heightInches) {
return suggestedName;
}
});
wordToHtmlConverter.processDocument(wordDocument);
List pics = wordDocument.getPicturesTable().getAllPictures();
if (pics != null) {
for (int i = 0; i < pics.size(); i++) {
Picture pic = (Picture) pics.get(i);
try {
pic.writeImageContent(new FileOutputStream(path
+ pic.suggestFullFileName()));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Document htmlDocument = wordToHtmlConverter.getDocument();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
DOMSource domSource = new DOMSource(htmlDocument);
StreamResult streamResult = new StreamResult(outStream);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.METHOD, "html");
serializer.transform(domSource, streamResult);
outStream.close();
String content = new String(outStream.toByteArray());
FileUtils.writeStringToFile(new File(path, "人员选择系分.html"), content, "utf-8");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# excel转html
package excelToHtml;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.converter.ExcelToHtmlConverter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.w3c.dom.Document;
public class PoiExcelToHtml {
final static String path = "D:\\poi-test\\excelToHtml\\";
final static String file = "exportExcel.xls";
public static void main(String args[]) throws Exception {
InputStream input=new FileInputStream(path+file);
HSSFWorkbook excelBook=new HSSFWorkbook(input);
ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter (DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() );
excelToHtmlConverter.processWorkbook(excelBook);
List pics = excelBook.getAllPictures();
if (pics != null) {
for (int i = 0; i < pics.size(); i++) {
Picture pic = (Picture) pics.get (i);
try {
pic.writeImageContent (new FileOutputStream (path + pic.suggestFullFileName() ) );
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Document htmlDocument =excelToHtmlConverter.getDocument();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
DOMSource domSource = new DOMSource (htmlDocument);
StreamResult streamResult = new StreamResult (outStream);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty (OutputKeys.ENCODING, "utf-8");
serializer.setOutputProperty (OutputKeys.INDENT, "yes");
serializer.setOutputProperty (OutputKeys.METHOD, "html");
serializer.transform (domSource, streamResult);
outStream.close();
String content = new String (outStream.toByteArray() );
FileUtils.writeStringToFile(new File (path, "exportExcel.html"), content, "utf-8");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# ppt转html
其实只是ppt转图片,有了图片后放到页面上去,点击下一页就一张张显示就可以了。这里只介绍ppt转图片的过程。
package pptToImg;
import java.awt.Dimension;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import org.apache.poi.hslf.model.TextRun;
import org.apache.poi.hslf.record.Slide;
import org.apache.poi.hslf.usermodel.RichTextRun;
import org.apache.poi.hslf.usermodel.SlideShow;
public class PPTtoImage {
public static void main(String[] args) {
// 读入PPT文件
File file = new File("D:/poi-test/pptToImg/test.ppt");
doPPTtoImage(file);
}
public static boolean doPPTtoImage(File file) {
boolean isppt = checkFile(file);
if (!isppt) {
System.out.println("The image you specify don't exit!");
return false;
}
try {
FileInputStream is = new FileInputStream(file);
SlideShow ppt = new SlideShow(is);
is.close();
Dimension pgsize = ppt.getPageSize();
org.apache.poi.hslf.model.Slide[] slide = ppt.getSlides();
for (int i = 0; i < slide.length; i++) {
System.out.print("第" + i + "页。");
TextRun[] truns = slide[i].getTextRuns();
for ( int k=0;k<truns.length;k++){
RichTextRun[] rtruns = truns[k].getRichTextRuns();
for(int l=0;l<rtruns.length;l++){
int index = rtruns[l].getFontIndex();
String name = rtruns[l].getFontName();
rtruns[l].setFontIndex(1);
rtruns[l].setFontName("宋体");
// System.out.println(rtruns[l].getText());
}
}
BufferedImage img = new BufferedImage(pgsize.width,pgsize.height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
graphics.setPaint(Color.BLUE);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
slide[i].draw(graphics);
// 这里设置图片的存放路径和图片的格式(jpeg,png,bmp等等),注意生成文件路径
FileOutputStream out = new FileOutputStream("D:/poi-test/pptToImg/pict_"+ (i + 1) + ".jpeg");
javax.imageio.ImageIO.write(img, "jpeg", out);
out.close();
}
System.out.println("success!!");
return true;
} catch (FileNotFoundException e) {
System.out.println(e);
// System.out.println("Can't find the image!");
} catch (IOException e) {
}
return false;
}
// function 检查文件是否为PPT
public static boolean checkFile(File file) {
boolean isppt = false;
String filename = file.getName();
String suffixname = null;
if (filename != null && filename.indexOf(".") != -1) {
suffixname = filename.substring(filename.indexOf("."));
if (suffixname.equals(".ppt")) {
isppt = true;
}
return isppt;
} else {
return isppt;
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# html导出pdf、word
pom文件调整,新增依赖
<!-- https://mvnrepository.com/artifact/com.itextpdf/html2pdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>2.1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf/itext7-core -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>7.1.7</version>
<type>pom</type>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
- 因为有纸张转向问题,所以复杂一些,否则直接HtmlConverter.convertToPdf()即可
public FileVO exportPdfToFtp(DocumentNameEnum documentNameEnum,Object data){
String htmlContent =FreeMarkerUtil.getFtlContent(documentNameEnum.getCode(),data);
try(ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
String fontsPath = Objects.requireNonNull(ClassUtils.getDefaultClassLoader().getResource("/template")).getPath();
FontProvider fontProvider = new DefaultFontProvider();
fontProvider.addDirectory(fontsPath);
ConverterProperties converterProperties = new ConverterProperties();
converterProperties.setFontProvider(fontProvider);
converterProperties.setCharset(StandardCharsets.UTF_8.displayName());
PdfWriter pdfWriter = new PdfWriter(bos);
PdfDocument pdfDocument = new PdfDocument(pdfWriter);
if (documentNameEnum.isNeedRotate()){
pdfDocument.setDefaultPageSize(PageSize.A4.rotate());
}
Document document = HtmlConverter.convertToDocument(htmlContent, pdfDocument,converterProperties);
document.close();
return FtpUtil.uploadPdfFile(bos
, documentNameEnum.getName("pdf")
, documentNameEnum.getMediaPathEnum().getPath());
} catch (Exception e){
log.error(e.getMessage());
throw new BusinessException("01","pdf文件生成失败:"+e.getMessage());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# thymeleaf2PDF
# js客户端解决pdf
# 安装使用
一般情况下我们会考虑使用包管理,常见的就是npm了,因此安装非常简单
npm install jspdf --save
1
或者也可以使用yarn
yarn add jspdf
1
接下来就是制作你的文件的时候了
默认导出为a4纸张,纵向,使用毫米表示单位
var doc = new jsPDF()
doc.text('Hello world!', 10, 10)
doc.save('a4.pdf')
1
2
3
2
3
如果要更改纸张尺寸,方向或单位,可以执行以下操作:
var doc = new jsPDF({
orientation: 'landscape',
unit: 'in',
format: [4, 2]
})
doc.text('Hello world!', 1, 1)
doc.save('two-by-four.pdf')
1
2
3
4
5
6
7
2
3
4
5
6
7