/*
* Copyright (c) 2018, QiJuBian and/or its affiliates. All rights reserved.
* QiJuBian PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.qijubian.commons;
import com.aspose.cells.License;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
/**
* Pdfs.java
* <pre>
* public static void main(String[] args) {
* try {
* Pdfs.wordToPdf(new FileInputStream("D:/xxx.docx"), "test.pdf", "/");
* } catch (FileNotFoundException e) {
* e.printStackTrace();
* }
* }
* </pre>
*
* @author hongquanli <hongquanli@qq.com>
* @version 1.0 2019-08-02 23:26
*/
public class Pdfs {
private static Logger logger = LoggerFactory.getLogger(Pdfs.class);
// 凭证
private static final String LICENSE_TEXT = "" +
"<License>\n" +
" <Data>\n" +
" <Products>\n" +
" <Product>Aspose.Total for Java</Product>\n" +
" <Product>Aspose.Words for Java</Product>\n" +
" </Products>\n" +
" <EditionType>Enterprise</EditionType>\n" +
" <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +
" <LicenseExpiry>20991231</LicenseExpiry>\n" +
" <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
" </Data>\n" +
" <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
"</License>";
/**
* WORD 转 PDF
*
* @param is WORD流
* @param fileName pdf文件名
* @param targetPath 指定生成路径
*/
public static void wordToPdf(
InputStream is, String fileName, String targetPath
) {
try {
com.aspose.words.Document doc = new com.aspose.words.Document(is);
FileClients.StoreFileRequest request = new FileClients.StoreFileRequest();
request.setFileName(fileName);
// request.setOriginalName(originalName);
request.setUploadPath(targetPath);
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
doc.save(out, com.aspose.words.SaveFormat.PDF);
request.setInputStream(new ByteArrayInputStream(out.toByteArray()));
}
FileClients.storeFile(request);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e);
}
}
/**
* WORD 转 PDF
*
* @param filepath WORD路径
* @param targetPath 指定生成路径
*/
public static void wordToPdf(String filepath, String targetPath) {
try {
/*
InputStream in = Excels.class.getClassLoader().getResourceAsStream("license.xml");
License license = new License();
license.setLicense(in);
*/
com.aspose.words.Document doc = new com.aspose.words.Document(filepath);
File file = new File(targetPath);
if (!file.getParentFile().exists()) {
// file.getParentFile().mkdirs();
Files.createDirectories(file.getParentFile().toPath());
}
try (FileOutputStream out = new FileOutputStream(file)) {
doc.save(out, com.aspose.words.SaveFormat.PDF);
// out.close();
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e);
}
}
/**
* EXCEL 转 PDF
*
* @param is EXCEL流
* @param fileName pdf文件名
* @param targetPath 指定生成路径
*/
public static void excelToPdf(
InputStream is, String fileName, String targetPath
) {
try {
/*
InputStream in = Excels.class.getClassLoader().getResourceAsStream("license.xml");
License license = new License();
license.setLicense(in);
*/
InputStream in = new ByteArrayInputStream(LICENSE_TEXT.getBytes(StandardCharsets.UTF_8));
License license = new License();
license.setLicense(in);
com.aspose.cells.Workbook wb = new com.aspose.cells.Workbook(is);
/*
WorksheetCollection collection = wb.getWorksheets();
List<String> names = new ArrayList<>();
collection.forEach(w -> {
Worksheet worksheet = (Worksheet) w;
if (!worksheet.getName().equals(sheetName)) {
names.add(worksheet.getName());
}
});
names.forEach(n -> wb.getWorksheets().removeAt(n));
*/
FileClients.StoreFileRequest request = new FileClients.StoreFileRequest();
request.setFileName(fileName);
request.setUploadPath(targetPath);
// request.setOriginalName(originalName);
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
wb.save(out, com.aspose.cells.SaveFormat.PDF);
request.setInputStream(new ByteArrayInputStream(out.toByteArray()));
}
FileClients.storeFile(request);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e);
}
}
/**
* EXCEL 转 PDF
*
* @param filepath EXCEL路径
* @param targetPath 指定生成路径
*/
public static void excelToPdf(String filepath, String targetPath) {
try {
/*
InputStream in = Excels.class.getClassLoader().getResourceAsStream("license.xml");
License license = new License();
license.setLicense(in);
*/
InputStream in = new ByteArrayInputStream(LICENSE_TEXT.getBytes(StandardCharsets.UTF_8));
License license = new License();
license.setLicense(in);
com.aspose.cells.Workbook wb = new com.aspose.cells.Workbook(filepath);
/*
WorksheetCollection collection = wb.getWorksheets();
List<String> names = new ArrayList<>();
collection.forEach(w -> {
Worksheet worksheet = (Worksheet) w;
if (!worksheet.getName().equals(sheetName)) {
names.add(worksheet.getName());
}
});
names.forEach(n -> wb.getWorksheets().removeAt(n));
*/
File file = new File(targetPath);
if (!file.getParentFile().exists()) {
// file.getParentFile().mkdirs();
Files.createDirectories(file.getParentFile().toPath());
}
try (FileOutputStream out = new FileOutputStream(file)) {
wb.save(out, com.aspose.cells.SaveFormat.PDF);
// out.close();
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e);
}
}
/**
* 图片转PDF
*
* @param is 图片流
* @param fileName pdf文件名
* @param targetPath 目标目录
*/
@SuppressWarnings("Duplicates")
public static void imageToPdf(
InputStream is, String fileName, String targetPath
) {
com.itextpdf.text.Document document = new com.itextpdf.text.Document(
PageSize.A4, 8, 8, 8, 8
);
try {
FileClients.StoreFileRequest request = new FileClients.StoreFileRequest();
request.setFileName(fileName);
request.setUploadPath(targetPath);
// request.setOriginalName(originalName);
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
PdfWriter.getInstance(document, out);
document.open();
// document.newPage();
// document.add(new Paragraph("Test"));
Image image = Image.getInstance(toBytes(is));
float height = image.getHeight();
float width = image.getWidth();
float percent = getPercent(width, height);
image.setAlignment(Image.MIDDLE);
// 表示是原来图像的比例;
image.scalePercent(percent);
document.add(image);
out.close();
document.close();
request.setInputStream(new ByteArrayInputStream(out.toByteArray()));
}
FileClients.storeFile(request);
} catch (DocumentException | IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
/**
* 图片转PDF
*
* @param images the images
* @param pdfFileName the pdfFileName
* @return the pdf
*/
@SuppressWarnings("Duplicates")
public static String imageToPdf(List<String> images, String pdfFileName) {
com.itextpdf.text.Document document = new com.itextpdf.text.Document(
PageSize.A4, 8, 8, 8, 8
);
try {
PdfWriter.getInstance(document, new FileOutputStream(pdfFileName));
document.open();
for (String imagePath : images) {
document.newPage();
// document.add(new Paragraph("Test"));
Image image = Image.getInstance(toBytes(imagePath));
float height = image.getHeight();
float width = image.getWidth();
float percent = getPercent(width, height);
image.setAlignment(Image.MIDDLE);
// 表示是原来图像的比例;
image.scalePercent(percent);
document.add(image);
}
document.close();
} catch (DocumentException | IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
return pdfFileName;
}
private static byte[] toBytes(String filePath) {
File file = new File(filePath);
FileInputStream fis;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
throw new RuntimeException(e.getMessage(), e);
}
return toBytes(fis);
}
private static byte[] toBytes(InputStream fis) {
byte[] buffer;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
return buffer;
}
/**
* 按宽度缩放
*
* @param w the width
* @param h the height
* @return the percent
*/
private static float getPercent(float w, float h) {
float p = 0.0f;
if (w > PageSize.A4.getWidth() - 16) {
p = (PageSize.A4.getWidth() - 16) / w * 100;
}
return p;
}
}
WORD、EXCEL、图片转PDF
最新推荐文章于 2024-08-08 07:19:07 发布
本文介绍了一个实用的工具类,能够将Word文档、Excel表格及图片文件转换为PDF格式,并提供了多种使用场景下的转换方法。
8599

被折叠的 条评论
为什么被折叠?



