vba调用官方 office

官方文档:https://learn.microsoft.com/zh-cn/office/vba/api/word.document.exportasfixedformat

这个不管过么复杂的word 格式都可以转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
On Error Resume Next
If WScript.Arguments.Count < 2 Then
WScript.Echo "Usage: script.vbs <input_file> <output_file>"
WScript.Quit 1
End If

Const wdExportFormatPDF = 17
source = WScript.Arguments.Item(0)
target = WScript.Arguments.Item(1)
Set oWord = WScript.CreateObject("Word.Application")
Set oDoc=oWord.Documents.Open(source)
odoc.ExportAsFixedFormat target,wdExportFormatPDF
odoc.Close
oword.Quit
Set oDoc=Nothing
Set oWord =Nothing
Const statusCode = 0
WScript.Echo statusCode

java 调用

1
2
3
4
5
6
7
8
9
10
11
12
public static boolean exec2Pdf(String wordPath, String pdfPath) {
String vbsFilePath = "C:\\Users\\shuzhuo\\Desktop\\word2pdf\\aaa.txt.vbs";
return exec2Pdf(vbsFilePath, wordPath, pdfPath);
}

public static boolean exec2Pdf(String vbsFilePath, String wordPath, String pdfPath) {
String cmd = StrUtil.format("cscript //nologo {} {} {}", vbsFilePath, wordPath, pdfPath);
String result = RuntimeUtil.execForStr(cmd);
System.out.println(result);
result = StrUtil.removeSuffix(result, "\r\n");
return StringUtils.equals(result, "0");
}

pandoc

强大的格式转换工具,不过这里只使用了docxpdf, 不过用一份复杂的报告转还是有格式错乱问题

https://github.com/jgm/pandoc

https://pandoc.org/installing.html#

window 下docker使用

1
2
3

docker run --rm --volume "%cd%:/data" --volume C:\Users\shuzhuo\Desktop\文档\font:/usr/share/fonts pandoc/extra --pdf-engine=xelatex --template=eisvogel --variable mainfont="SimSun" 1.docx -o 2.pdf

aspose

强大的工具,使用过多个版本,每个版本还是会有些格式问题。这里使用过的版本是

1
16.4.0-jdk16 、20.12.17、 22.12.01  
1
2
3
4
5
6
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>20.12.17</version>
<classifier>jdk17</classifier>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static void wordToPdf(String srcFile, String descFile) throws GlobalIncorrectPasswordException {
try {
PdfSaveOptions options = new PdfSaveOptions();
options.setSaveFormat(SaveFormat.PDF);
// pdf目录
options.getOutlineOptions().setHeadingsOutlineLevels(9);

Document document = new Document(srcFile);
document.save(descFile, options);
} catch (IncorrectPasswordException e) {
throw new GlobalIncorrectPasswordException("该文档已加密,或文档内部引用的文件已加密,请检查");
} catch (Exception e) {
log.error("word转pdf失败");
throw new RuntimeException(e);
}
}