通过第三方插件aspose.Cells实现。
import com.aspose.cells.*;
public class CellsFileConvert{
/**
* pdf文件后缀
*/
final String FILE_PDF_SUFFIX = ".pdf";
private String excelToPdf(String filePath) {
String str =
"<License>\n" +
" <Data>\n" +
" <Products>\n" +
" <Product>Aspose.Total 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>";
//pdf文件的保存路径
String pdfPath = filePath.substring(0, filePath.lastIndexOf(".")) + FILE_PDF_SUFFIX;
try (InputStream is = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
FileOutputStream os = new FileOutputStream(pdfPath)) {
//支持正版
License license = new License();
license.setLicense(is);
Workbook workbook = new Workbook(filePath);
//pdf页面有其他要求可以用PdfSaveOptions进行调整
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
//所有列缩放到一个页面
pdfSaveOptions.setOnePagePerSheet(true);
workbook.save(os, pdfSaveOptions);
return pdfPath;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
CellsFileConvert cellsFileConvert = new CellsFileConvert();
String pdfPath = cellsFileConvert.excelToPdf("D:\\file\\test.xlsx");
System.out.println(pdfPath);
}
}
通过PdfSaveOptions可以修改生成的pdf文件.
支持正版