1、Aspose组件下载
Aspose下载地址:https://products.aspose.com/words/java
破解版下载地址:https://download.csdn.net/download/ahgaoyong/9615854
官方文档地址:https://docs.aspose.com/display/wordsjava/Home
官方Demo代码:https://github.com/aspose-words/Aspose.Words-for-Java
2、多张图片转成pdf
1) 验证license
/**
* 获取license
*
* @return
*/
public static boolean getLicense() {
boolean result = false;
try {
InputStream is = Test.class.getClassLoader().getResourceAsStream("\\license.xml");
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
2) 多图片转成pdf
public static void convertImageToPdf(ArrayList<String> inputImgPaths, String outputFileName) throws Exception
{
// 验证License
if (!getLicense()) {
return;
}
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
try
{
for (int i = 0; i < inputImgPaths.size(); i++)
{
if (i != 0)
builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
File file = new File(inputImgPaths.get(i));// 本地图片
BufferedImage image = (BufferedImage) ImageIO.read(file);
double maxPageHeight = 1584;
double maxPageWidth = 1584;
double currentImageHeight = ConvertUtil.pixelToPoint(image.getHeight());
double currentImageWidth = ConvertUtil.pixelToPoint(image.getWidth());
if (currentImageWidth >= maxPageWidth || currentImageHeight >= maxPageHeight)
{
double[] size = CalculateImageSize(image, maxPageHeight, maxPageWidth, currentImageHeight,
currentImageWidth);
currentImageWidth = size[0];
currentImageHeight = size[1];
}
PageSetup ps = builder.getPageSetup();
ps.setPageWidth(currentImageWidth);
ps.setPageHeight(currentImageHeight);
Shape shape = builder.insertImage(
image,
RelativeHorizontalPosition.PAGE,
0,
RelativeVerticalPosition.PAGE,
0,
ps.getPageWidth(),
ps.getPageHeight(),
WrapType.NONE);
}
}
finally {
}
// Save the document to PDF.
doc.save(outputFileName);
}
// 等比计算图片尺寸
public static double[] CalculateImageSize(BufferedImage img, double containerHeight, double containerWidth,
double targetHeight, double targetWidth) throws Exception {
// Calculate width and height
targetHeight = containerHeight;
targetWidth = containerWidth;
// Get size of an image
double imgHeight = ConvertUtil.pixelToPoint(img.getHeight());
double imgWidth = ConvertUtil.pixelToPoint(img.getWidth());
if (imgHeight < targetHeight && imgWidth < targetWidth)
{
targetHeight = imgHeight;
targetWidth = imgWidth;
}
else
{
// 计算文档中图像的大小
double ratioWidth = imgWidth / targetWidth;
double ratioHeight = imgHeight / targetHeight;
if (ratioWidth > ratioHeight)
targetHeight = (targetHeight * (ratioHeight / ratioWidth));
else
targetWidth = (targetWidth * (ratioWidth / ratioHeight));
}
double[] size = new double[2];
size[0] = targetWidth; // width
size[1] = targetHeight; // height
return (size);
}
相关文档:
java aspose.cells Excel(.xls,.xlsx)文件转成csv文件和html文件
java利用aspose组件将word转成pdf 中文乱码问题