Java生成PDF说明。以下介绍了采用SpringBoot动态引入相关包,例如ofd、txt、ppt、pptx等文件格式不能直接生成图片,可以先转化为PDF的时候再进行生成图片。使用场景是需要将项目的过程资料,或这个多个表格融合在一个pdf打印成册时,可以使用代码来管理实现。以下代码可以直接上手适用于初学者,当然如果有更好的方法可以留言哟。
第一步:引入以下包,我测试了txt、doc、docx、xls、xlsx、ppt、pptx、pdf、ofd生成图片是没有问题。(直接粘贴可使用)
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.1</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.4</version>
</dependency>
<dependency>
<groupId>org.ofdrw</groupId>
<artifactId>ofdrw-full</artifactId>
<version>1.8.6</version>
</dependency>
<dependency>
<groupId>com.aspose-cells</groupId>
<artifactId>aspose-cells</artifactId>
<version>8.5.2.0</version>
</dependency>
<dependency>
<groupId>com.aspose-pdf</groupId>
<artifactId>aspose-pdf</artifactId>
<version>20.10</version>
</dependency>
<dependency>
<groupId>com.aspose-words</groupId>
<artifactId>aspose-words</artifactId>
<version>15.8.0.0</version>
</dependency>
<dependency>
<groupId>com.aspose.slides</groupId>
<artifactId>aspose.slides</artifactId>
<version> 15.9.0</version>
</dependency>
第二步:使用Aspos需要License,这个可以在Aspose官网下载,我贴了一段可以使用的,新上手的小伙伴,可以直接使用。
license.xml:
<License>
<Data>
<Products>
<Product>Aspose.Total for Java</Product>
<Product>Aspose.Words for Java</Product>
</Products>
<EditionType>Enterprise</EditionType>
<SubscriptionExpiry>20991231</SubscriptionExpiry>
<LicenseExpiry>20991231</LicenseExpiry>
<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
</Data>
<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>
第三步:我写个校验license的方法
AsposeLicenseUtil.class:
private static Map<String, Boolean> map = new HashMap<>();
public static boolean judgeLicense(String type) {
if(map.containsKey(type)) {
return map.get(type);
} else {
boolean result = false;
InputStream is = AsposeLicenseUtil.class.getClassLoader().getResourceAsStream("license.xml");
try {
switch (type) {
case "word":
case "txt":
case "ofd":
new com.aspose.words.License().setLicense(is);
break;
case "excel":
new com.aspose.cells.License().setLicense(is);
break;
case "ppt":
new com.aspose.slides.License().setLicense(is);
break;
case "pdf":
new com.aspose.pdf.License().setLicense(is);
//logger.info("设置License成功");
break;
default:
logger.info("校验License失败,类型错误!");
}
result = true;
} catch (Exception e) {
logger.info("校验License失败" + e.getLocalizedMessage());
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
map.put(type, result);
return result;
}
}
第四步实现txt、doc、docx、xls、xlsx、ppt、pptx、pdf、ofd生成图片
FileImgUtils.class:
/**
* txt、doc、docx、xls、xlsx、ppt、pptx、pdf、ofd生成图片
*
* @param sourceFilePath
* @param imgFullPath
* @param type
*/
public static void fileToImg(String sourceFilePath, String imgFullPath, String type, String ztPath) {
long old = System.currentTimeMillis();
logger.info("开始生成图片>>>>>>");
try {
// 校验License
AsposeLicenseUtil.judgeLicense(type);
if ("txt".equals(type)) {
txtToImg(sourceFilePath, imgFullPath, ztPath);
} else if ("word".equals(type)) {
wordToImg(sourceFilePath, imgFullPath);
} else if ("ofd".equals(type)) {
ofdToImg(sourceFilePath, imgFullPath);
} else if ("excel".equals(type)) {
excelToImg(sourceFilePath, imgFullPath);
} else if ("ppt".equals(type)) {
pptToImg(sourceFilePath, imgFullPath);
} else if ("pdf".equals(type)) {
pdfToImg(sourceFilePath, imgFullPath);
} else {
logger.info("暂不支持该类型:" + type);
}
} catch (Exception e) {
logger.info("生成图片失败");
e.printStackTrace();
}
long now = System.currentTimeMillis();
logger.info("生成图片结束<<<<<<");
logger.info("生成图片耗时:" + ((now - old) / 1000.0) + "秒");
}
public static void text2pdf(String txt, String pdf, String ztPath) {
File file = new File(ztPath + "/fonts/simkai.ttf");
com.itextpdf.text.Document document = new com.itextpdf.text.Document();
try {
OutputStream os;
File pdffile = new File(pdf);
os = new FileOutputStream(pdffile);
PdfWriter.getInstance(document, os);
document.open();
// 方法一:使用Windows系统字体(TrueType)
// BaseFont baseFont = BaseFont.createFont(file.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// Font font = new Font(baseFont);
BaseFont bfComic = BaseFont.createFont(file.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
float fontsize = 12f;
Font font = new Font(bfComic, fontsize, Font.NORMAL);
InputStreamReader isr = new InputStreamReader(new FileInputStream(new File(txt)), "UTF-8");
@SuppressWarnings("resource")
BufferedReader bufferedReader = new BufferedReader(isr);
String str = "";
while ((str = bufferedReader.readLine()) != null) {
document.add(new Paragraph(str, font));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
document.close();
} catch (Exception e) {
logger.info("关闭资源失败");
e.printStackTrace();
}
}
}
/**
* txt生成图片
*
* @param txtPath
* @param imgFullPathName
*/
private static void txtToImg(String txtPath, String imgFullPathName, String ztPath) {
// 获取文件后缀名
int separatorlastIndex = txtPath.lastIndexOf(File.separator);
// 文件夹路径
String folderPath = txtPath.substring(0, separatorlastIndex);
// xxx.txt
String pptName = txtPath.substring(separatorlastIndex, txtPath.length());
// xxx.pdf
String pdfName = pptName.substring(0, pptName.lastIndexOf(".")) + ".pdf";
// xxx/xxx/temp/xxx.pdf
String pdfPath = folderPath + File.separator + "txttemp" + pdfName;
// 如果临时文件不存,就创建
File file = new File(folderPath + File.separator + "txttemp");
if (!file.exists()) {
file.mkdirs();
}
// FileOutputStream os = null;
// Document doc;
try {
text2pdf(txtPath, pdfPath, ztPath);
// 输出流
// os = new FileOutputStream(pdfPath);
// doc = new Document(txtPath);
// doc.save(os, com.aspose.words.SaveFormat.PDF);
// 生成图片
pdfToImg(pdfPath, imgFullPathName);
} catch (Exception e) {
logger.info("txt转pdf失败");
e.printStackTrace();
} finally {
// try {
// os.close();
// } catch (IOException e) {
// logger.info("关闭资源失败");
// e.printStackTrace();
// }
}
}
/**
* ofd生成图片
*
* @param txtPath
* @param imgFullPathName
*/
private static void ofdToImg(String ofdPath, String imgFullPathName) {
// 获取文件后缀名
int separatorlastIndex = ofdPath.lastIndexOf(File.separator);
// 文件夹路径
String folderPath = ofdPath.substring(0, separatorlastIndex);
// xxx.ofd
String pptName = ofdPath.substring(separatorlastIndex, ofdPath.length());
// xxx.pdf
String pdfName = pptName.substring(0, pptName.lastIndexOf(".")) + ".pdf";
// xxx/xxx/temp/xxx.pdf
String pdfPath = folderPath + File.separator + "ofdtemp" + pdfName;
// 如果临时文件不存,就创建
File file = new File(folderPath + File.separator + "ofdtemp");
if (!file.exists()) {
file.mkdirs();
}
FileOutputStream os = null;
Document doc;
try {
Path input = Paths.get(ofdPath);
Path output = Paths.get(pdfPath);
ofd2pdf(input, output);
// 生成图片
pdfToImg(pdfPath, imgFullPathName);
// 输出流
// os = new FileOutputStream(pdfPath);
// doc = new Document(ofdPath);
// doc.save(os, com.aspose.words.SaveFormat.PDF);
} catch (Exception e) {
logger.info("txt转pdf失败");
e.printStackTrace();
}
}
/**
* word生成图片(第一页下标从0开始)
*
* @param docPath
* @param imgFullPathName
*/
private static void wordToImg(String docPath, String imgFullPathName) {
// String filename = Path.GetFileNameWithoutExtension(filePath).ToLower();
Document words = null;
try {
words = new Document(docPath);
} catch (Exception e) {
logger.info("创建word对象失败");
e.printStackTrace();
}
// 创建image对象,设置图片格式,分辨率
ImageSaveOptions imageSaveOptions = new ImageSaveOptions(SaveFormat.PNG);
imageSaveOptions.setResolution(128);
int pagecount = 0;
try {
pagecount = words.getPageCount();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
for (int pageindex = 0; pageindex < pagecount; pageindex++) {
try {
File file = new File(imgFullPathName + "//img" + pageindex + ".png");
// 如果不存在,先创建一个文件占位,但没有图片内容
if (!file.exists()) {
file.createNewFile();
}
imageSaveOptions.setPageIndex(pageindex);
words.save(file.getPath(), imageSaveOptions);
} catch (Exception e) {
logger.info("word生成图片失败");
e.printStackTrace();
}
}
}
/**
* excel生成图片
*
* @param excelPath
* @param imgFullPathName
*/
private static void excelToImg(String excelPath, String imgFullPathName) {
Workbook book = null;
try {
book = new Workbook(excelPath);
} catch (Exception e1) {
logger.info("创建excel对象失败");
e1.printStackTrace();
}
// 创建一个图表选项的对象
ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();
imgOptions.setCellAutoFit(true);
imgOptions.setOnePagePerSheet(true);
imgOptions.setImageFormat(ImageFormat.getPng());
// 获取所有sheet页
WorksheetCollection worksheets = book.getWorksheets();
int count = worksheets.getCount();
// File file = new File(imgFullPathName);
int i = 0;
for (int index = 0; index < count; index++) {
// 获取第一张sheet页
Worksheet sheet = worksheets.get(index);
// 设置图片数据的边距
// A列-L列,1行-39行
String area = "A1:L39";
sheet.getPageSetup().setPrintArea(area);
sheet.getPageSetup().setLeftMargin(1);
sheet.getPageSetup().setRightMargin(1);
sheet.getPageSetup().setTopMargin(1);
sheet.getPageSetup().setBottomMargin(1);
// 设置字体样式(包含中文)
// CellsHelper.setFontDir("/");
// 创建一个纸张底色渲染对象
SheetRender sr = null;
try {
sr = new SheetRender(sheet, imgOptions);
for (int j = 0; j < sr.getPageCount(); j++) {
File file = new File(imgFullPathName + "//img" + i + ".png");
if (!file.exists()) {
sr.toImage(j, file.getPath());
}
i = i + 1;
}
} catch (Exception e) {
logger.info("excel生成图片失败");
e.printStackTrace();
}
}
}
/**
* pdf生成图片(第一页下标从1开始)
*
* @param pdfPath
* @param imgFullPathName
*/
private static void pdfToImg1(String pdfPath, String imgFullPathName) {
com.aspose.pdf.Document pdf = new com.aspose.pdf.Document(pdfPath);
PageCollection pages = pdf.getPages();
// pdf总页数
int size = pages.size();
/**
* 图片宽度:800 图片高度:100 分辨率 960 Quality [0-100] 最大100 new JpegDevice(800, 1000,
* resolution, 90);
*/
JpegDevice jpegDevice = new JpegDevice(100);
// 生成的图片数
for (int index = 1; index < size + 1; index++) {
// 输出路径
FileOutputStream fileOs = null;
try {
// File file = new File(imgFullPathName);
File file = new File(imgFullPathName + "//img" + index + ".png");
if (!file.exists()) {
file.createNewFile();
}
fileOs = new FileOutputStream(file);
jpegDevice.process(pages.get_Item(index), fileOs);
} catch (IOException e) {
logger.info("PDF转换图片失败,失败原因" + e.getLocalizedMessage());
} finally {
try {
fileOs.flush();
fileOs.close();
pdf.close();
} catch (IOException e) {
logger.info("关闭资源文件失败,失败原因:" + e.getLocalizedMessage());
}
}
}
// 如果此pdf是ppt转换而成,删除pdf
if (pdfPath.contains("pdftemp") || pdfPath.contains("txttemp")) {
File file = new File(pdfPath);
if (file.exists()) {
file.delete();
}
}
}
/**
* pdf生成图片(第一页下标从1开始)
*
* @param pdfPath
* @param imgFullPathName
*/
private static void pdfToImg(String pdfPath, String imgFullPathName) {
PDDocument doc = null;
ByteArrayOutputStream os = null;
InputStream stream = null;
OutputStream out = null;
try {
// pdf路径
stream = new FileInputStream(pdfPath);
// 加载解析PDF文件
doc = PDDocument.load(stream);
PDFRenderer pdfRenderer = new PDFRenderer(doc);
PDPageTree pages = doc.getPages();
int pageCount = pages.getCount();
for (int i = 0; i < pageCount; i++) {
BufferedImage bim = pdfRenderer.renderImageWithDPI(i, 200);
os = new ByteArrayOutputStream();
ImageIO.write(bim, "png", os);
byte[] dataList = os.toByteArray();
// jpg文件转出路径
File file = new File(imgFullPathName + "//img" + i + ".png");
if (!file.getParentFile().exists()) {
// 不存在则创建父目录及子文件
file.getParentFile().mkdirs();
file.createNewFile();
}
out = new FileOutputStream(file);
out.write(dataList);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (doc != null){
try {
doc.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (os != null){
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (stream != null){
try {
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (out != null){
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// 如果此pdf是ppt转换而成,删除pdf
if (pdfPath.contains("pdftemp") || pdfPath.contains("txttemp")) {
File file = new File(pdfPath);
if (file.exists()) {
file.delete();
}
}
}
/**
* ppt生成图片
*
* @param pptPath
* @param imgFullPathName
*/
private static void pptToImg(String pptPath, String imgFullPathName) {
Presentation ppt = new Presentation(pptPath);
// 获取文件后缀名
int separatorlastIndex = pptPath.lastIndexOf(File.separator);
// 文件夹路径
String folderPath = pptPath.substring(0, separatorlastIndex);
// xxx.ppt
String pptName = pptPath.substring(separatorlastIndex, pptPath.length());
// xxx.pdf
String pdfName = pptName.substring(0, pptName.lastIndexOf(".")) + ".pdf";
// xxx/xxx/temp/xxx.pdf
String pdfPath = folderPath + File.separator + "pdftemp" + pdfName;
// 如果临时文件不存,就创建
File file = new File(folderPath + File.separator + "pdftemp");
if (!file.exists()) {
file.mkdirs();
}
File pdffile = new File(pdfPath);
if (!pdffile.exists()) {
// 将ppt转pdf
ppt.save(pdfPath, com.aspose.slides.SaveFormat.Pdf);
}
File imgfile = new File(imgFullPathName);
if (!imgfile.exists()) {
// pdf生成图片
pdfToImg(pdfPath, imgFullPathName);
}
}