我是傲驕鹿先生,沉淀、學(xué)習(xí)、分享、成長。
如果你覺得文章內(nèi)容還可以的話,希望不吝您的「一鍵三連」,文章里面有不足的地方希望各位在評論區(qū)補(bǔ)充疑惑、見解以及面試中遇到的奇葩問法
面對日常開發(fā)過程中,將各種文件轉(zhuǎn)換為pdf文件的問題,總是讓人頭疼,這次終于完美解決了!
最好的效果無非就是在不限制文件大小、保持文件格式的情況下將文件轉(zhuǎn)換為pdf格式文件,而且轉(zhuǎn)換完成的文件不帶水印,這樣的效果應(yīng)該可以滿足很多需求了,之前在遇到這個問題的時(shí)候是使用spire.doc實(shí)現(xiàn)的,但效果很不好,每一頁都是帶水印的。下面將這是的方法展示給大家供大家參考。
一、集成aspose-words
實(shí)現(xiàn)文檔轉(zhuǎn)換為pdf文件需要的包是aspose-words-15.8.0,如果大家找不到包可以私信我,這里就不做鏈接了。
1、集成aspose-words-15.8.0
因?yàn)轫?xiàng)目中使用的是阿里云的maven倉庫,不能進(jìn)行導(dǎo)包,就需要手動的將包導(dǎo)入到項(xiàng)目中。如圖所示,將包放入到項(xiàng)目中。
包的位置是與src并列的位置,然后在pom文件中進(jìn)行配置:
除了上面手動導(dǎo)入的包之外,還有其他用的包,在pom文件中添加即可。
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.3</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j</artifactId>
<version>3.2.2</version>
</dependency>
<!-- 下面的依賴是為了報(bào)其他錯誤的 -->
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>5.0.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>SparseBitSet</artifactId>
<version>1.2</version>
</dependency>
<!-- 修改com.aspose.cells專用包 -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.26.0-GA</version>
</dependency>
二、編寫工具類
package com.dtech.common.utils.file;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import org.apache.poi.hslf.usermodel.*;
import org.apache.poi.xslf.usermodel.*;
import java.awt.*;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;
/**
* java將word、excel、ppt、圖片轉(zhuǎn)換為pdf文件
*/
public class PdfConverUtil {
/**
* @param inputStream 源文件輸入流
* @param outputStream pdf文件輸出流
**/
public static boolean imgToPdf(InputStream inputStream, OutputStream outputStream) {
Document document = null;
try {
// 創(chuàng)建文檔,設(shè)置PDF頁面的大小 A2-A9, 個人覺得A3最合適
document = new Document(PageSize.A3, 20, 20, 20, 20);
// 新建pdf文檔,具體邏輯看.getInstance方法
PdfWriter.getInstance(document, outputStream);
document.open();
document.newPage();
// 將文件流轉(zhuǎn)換為字節(jié)流,便于格式轉(zhuǎn)換
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int length = 0 ;
while (-1 != (length = bufferedInputStream.read(bytes))) {
byteArrayOutputStream.write(bytes, 0, length);
}
// 處理img圖片
Image image = Image.getInstance(byteArrayOutputStream.toByteArray());
float height = image.getHeight();
float width = image.getWidth();
float percent = 0.0f;
// 設(shè)置像素或者長寬高,將會影響圖片的清晰度,因?yàn)橹皇菍D片放大或縮小
if (height > width) {
// A4 - A9
percent = PageSize.A4.getHeight() / height * 100;
} else {
percent = PageSize.A4.getWidth() / width * 100;
}
image.setAlignment(Image.MIDDLE);
image.scalePercent(percent);
// 將圖片放入文檔中,完成pdf轉(zhuǎn)換
document.add(image);
// System.out.println("image轉(zhuǎn)換完畢");
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
if (document != null) {
document.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return true;
}
/**
* @param inputStream 源文件輸入流
* @param outputStream pdf文件輸出流
**/
public static boolean wordTopdfByAspose(InputStream inputStream, OutputStream outputStream) {
// 驗(yàn)證License 若不驗(yàn)證則轉(zhuǎn)化出的pdf文檔會有水印產(chǎn)生
if (!getLicense()) {
return false;
}
try {
// 將源文件保存在com.aspose.words.Document中,具體的轉(zhuǎn)換格式依靠里面的save方法
com.aspose.words.Document doc = new com.aspose.words.Document(inputStream);
// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,EPUB, XPS, SWF 相互轉(zhuǎn)換
doc.save(outputStream, SaveFormat.PDF);
// System.out.println("word轉(zhuǎn)換完畢");
} catch (Exception e) {
e.printStackTrace();
return false;
}finally {
if (outputStream != null) {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
// 官方文檔的要求 無需理會
public static boolean getLicense() {
boolean result = false;
try {
String s = "<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>";
ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* @param inputStream 源文件輸入流
* @param outputStream pdf文件輸出流
**/
public static boolean excelToPdf(InputStream inputStream, OutputStream outputStream) {
// 驗(yàn)證License 若不驗(yàn)證則轉(zhuǎn)化出的pdf文檔會有水印產(chǎn)生
if (!getExeclLicense()) {
return false;
}
try {
com.aspose.cells.Workbook wb = new com.aspose.cells.Workbook(inputStream);// 原始excel路徑
com.aspose.cells.PdfSaveOptions pdfSaveOptions = new com.aspose.cells.PdfSaveOptions();
pdfSaveOptions.setOnePagePerSheet(false);
int[] autoDrawSheets={3};
//當(dāng)excel中對應(yīng)的sheet頁寬度太大時(shí),在PDF中會拆斷并分頁。此處等比縮放。
autoDraw(wb,autoDrawSheets);
int[] showSheets={0};
//隱藏workbook中不需要的sheet頁。
printSheetPage(wb,showSheets);
wb.save(outputStream, pdfSaveOptions);
outputStream.flush();
outputStream.close();
System.out.println("excel轉(zhuǎn)換完畢");
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
/**
* 設(shè)置打印的sheet 自動拉伸比例
* @param wb
* @param page 自動拉伸的頁的sheet數(shù)組
*/
public static void autoDraw(com.aspose.cells.Workbook wb,int[] page){
if(null!=page&&page.length>0){
for (int i = 0; i < page.length; i++) {
wb.getWorksheets().get(i).getHorizontalPageBreaks().clear();
wb.getWorksheets().get(i).getVerticalPageBreaks().clear();
}
}
}
/**
* 隱藏workbook中不需要的sheet頁。
*
* @param wb
* @param page 顯示頁的sheet數(shù)組
*/
public static void printSheetPage(com.aspose.cells.Workbook wb, int[] page) {
for (int i = 1; i < wb.getWorksheets().getCount(); i++) {
wb.getWorksheets().get(i).setVisible(false);
}
if (null == page || page.length == 0) {
wb.getWorksheets().get(0).setVisible(true);
} else {
for (int i = 0; i < page.length; i++) {
wb.getWorksheets().get(i).setVisible(true);
}
}
}
public static boolean getExeclLicense() {
boolean result = false;
try {
String s = "<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>";
ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
com.aspose.cells.License aposeLic = new com.aspose.cells.License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* pptToPdf
* @param inputStream
* @param outputStream
* @return
*/
public static boolean pptToPdf(InputStream inputStream, OutputStream outputStream) {
Document document = null;
HSLFSlideShow hslfSlideShow = null;
PdfWriter pdfWriter = null;
try {
hslfSlideShow = new HSLFSlideShow(inputStream);
// 獲取ppt文件頁面
Dimension dimension = hslfSlideShow.getPageSize();
document = new Document();
// pdfWriter實(shí)例
pdfWriter = PdfWriter.getInstance(document, outputStream);
document.open();
PdfPTable pdfPTable = new PdfPTable(1);
List<HSLFSlide> hslfSlideList = hslfSlideShow.getSlides();
for (int i=0; i < hslfSlideList.size(); i++) {
HSLFSlide hslfSlide = hslfSlideList.get(i);
// 設(shè)置字體, 解決中文亂碼
for (HSLFShape shape : hslfSlide.getShapes()) {
HSLFTextShape textShape = (HSLFTextShape) shape;
for (HSLFTextParagraph textParagraph : textShape.getTextParagraphs()) {
for (HSLFTextRun textRun : textParagraph.getTextRuns()) {
textRun.setFontFamily("宋體");
}
}
}
BufferedImage bufferedImage = new BufferedImage((int)dimension.getWidth(), (int)dimension.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2d = bufferedImage.createGraphics();
graphics2d.setPaint(Color.white);
graphics2d.setFont(new Font("宋體", Font.PLAIN, 12));
hslfSlide.draw(graphics2d);
graphics2d.dispose();
Image image = Image.getInstance(bufferedImage, null);
image.scalePercent(50f);
// 寫入單元格
pdfPTable.addCell(new PdfPCell(image, true));
document.add(image);
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (document != null) {
document.close();
}
if (pdfWriter != null) {
pdfWriter.close();
}
}
// System.out.println("ppt轉(zhuǎn)換完畢");
return true;
}
/**
* pptxToPdf
* @param inputStream
* @param outputStream
* @return
*/
public static boolean pptxToPdf(InputStream inputStream, OutputStream outputStream) {
Document document = null;
XMLSlideShow slideShow = null;
PdfWriter pdfWriter = null;
try {
slideShow = new XMLSlideShow(inputStream);
Dimension dimension = slideShow.getPageSize();
document = new Document();
pdfWriter = PdfWriter.getInstance(document, outputStream);
document.open();
PdfPTable pdfPTable = new PdfPTable(1);
List<XSLFSlide> slideList = slideShow.getSlides();
for (int i = 0, row = slideList.size(); i < row; i++) {
XSLFSlide slide = slideList.get(i);
// 設(shè)置字體, 解決中文亂碼
for (XSLFShape shape : slide.getShapes()) {
XSLFTextShape textShape = (XSLFTextShape) shape;
for (XSLFTextParagraph textParagraph : textShape.getTextParagraphs()) {
for (XSLFTextRun textRun : textParagraph.getTextRuns()) {
textRun.setFontFamily("宋體");
}
}
}
BufferedImage bufferedImage = new BufferedImage((int)dimension.getWidth(), (int)dimension.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2d = bufferedImage.createGraphics();
graphics2d.setPaint(Color.white);
graphics2d.setFont(new Font("宋體", Font.PLAIN, 12));
slide.draw(graphics2d);
graphics2d.dispose();
Image image = Image.getInstance(bufferedImage, null);
image.scalePercent(50f);
// 寫入單元格
pdfPTable.addCell(new PdfPCell(image, true));
document.add(image);
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (document != null) {
document.close();
}
if (pdfWriter != null) {
pdfWriter.close();
}
}
System.out.println("pptx轉(zhuǎn)換完畢");
return true;
}
}
?三、使用工具類進(jìn)行文件轉(zhuǎn)換
完成工具類編寫就可以進(jìn)行文件轉(zhuǎn)換了,這里根據(jù)業(yè)務(wù),將word文件進(jìn)行上傳服務(wù)器,然后在將服務(wù)器的word文件轉(zhuǎn)換為pdf文件,訪問端即可進(jìn)行pdf文件預(yù)覽了。
續(xù):將代碼打包上傳至服務(wù)器后,轉(zhuǎn)換完成的pdf文件是亂碼
在window下沒有問題但是在linux下有問題,說明不是代碼或者輸入輸出流編碼的問題,原因是兩個平臺環(huán)境的問題。說明linux環(huán)境中缺少相應(yīng)的字體以供使用,可能會導(dǎo)致導(dǎo)出的文件字體亂碼,或者更新域錯亂問題。解決辦法如下:更新字體
1、在linux環(huán)境下安裝win字體,將win機(jī)器的C:\Windows\Fonts目錄下的全部文件拷貝到linux服務(wù)器字體安裝目錄下,然后執(zhí)行以下命令更新字體緩存。
2、linux服務(wù)器字體文件是在/usr/share/fonts文件夾下的,在fonts文件夾下新建一個文件夾chinese,然后把window環(huán)境中的字體上傳到服務(wù)器中
3、執(zhí)行命令,讓字體生效
cd /usr/share/fonts
sudo fc-cache -fv
?4、修改代碼,設(shè)置字體
文章來源:http://www.zghlxwxcb.cn/news/detail-773830.html
系列文章持續(xù)更新,微信搜一搜「傲驕鹿先生?」,回復(fù)【面試】有準(zhǔn)備的一線大廠面試資料。文章來源地址http://www.zghlxwxcb.cn/news/detail-773830.html
到了這里,關(guān)于aspose-words、itextpdf完美解決java將word、excel、ppt、圖片轉(zhuǎn)換為pdf文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!