提问人:Shaul Behr 提问时间:3/4/2009 更新时间:1/8/2020 访问量:396736
如何以编程方式将 Word 文件转换为 PDF?[关闭]
How do I convert Word files to PDF programmatically? [closed]
问:
我们不允许提出有关书籍、工具、软件库等建议的问题。您可以编辑问题,以便用事实和引文来回答。
4年前关闭。
去年,社群审查了是否要重新讨论这个问题,并关闭了这个问题:
原始关闭原因未解决
我找到了几个开源/免费软件程序,允许您将 .doc 文件转换为 .pdf 文件,但它们都是应用程序/打印机驱动程序的品种,没有附加 SDK。
我发现有几个程序确实具有SDK,允许您将.doc文件转换为.pdf文件,但它们都是专有类型,许可证2,000美元左右。
有谁知道使用 C# 或 VB.NET 解决我的问题的任何干净、廉价(最好是免费)的编程解决方案?
谢谢!
答:
这里似乎有一些相关信息:
在 ASP.NET 中将 MS Word 文档转换为 PDF
此外,由于 Office 2007 具有发布到 PDF 功能,我想您可以使用办公自动化在 Word 2007 中打开 *.DOC 文件并另存为 PDF。我不太热衷于办公自动化,因为它很慢而且容易挂起,但只是把它扔在那里......
评论
PDFCreator 具有一个 COM 组件,可从 .NET 或 VBScript 调用(下载中包含示例)。
但是,在我看来,打印机正是您所需要的 - 只需将其与 Word 的自动化功能混合在一起,您就可以开始了。
评论
使用 foreach 循环而不是 for 循环 - 它解决了我的问题。
int j = 0;
foreach (Microsoft.Office.Interop.Word.Page p in pane.Pages)
{
var bits = p.EnhMetaFileBits;
var target = path1 +j.ToString()+ "_image.doc";
try
{
using (var ms = new MemoryStream((byte[])(bits)))
{
var image = System.Drawing.Image.FromStream(ms);
var pngTarget = Path.ChangeExtension(target, "png");
image.Save(pngTarget, System.Drawing.Imaging.ImageFormat.Png);
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
j++;
}
这是对适用于我的程序的修改。它使用安装了“另存为 PDF”加载项的 Word 2007。它在目录中搜索 .doc 文件,在 Word 中打开它们,然后将它们另存为 PDF。请注意,您需要将对 Microsoft.Office.Interop.Word 的引用添加到解决方案中。
using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
...
// Create a new Microsoft Word application object
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
// C# doesn't have optional arguments so we'll need a dummy value
object oMissing = System.Reflection.Missing.Value;
// Get list of Word files in specified directory
DirectoryInfo dirInfo = new DirectoryInfo(@"\\server\folder");
FileInfo[] wordFiles = dirInfo.GetFiles("*.doc");
word.Visible = false;
word.ScreenUpdating = false;
foreach (FileInfo wordFile in wordFiles)
{
// Cast as Object for word Open method
Object filename = (Object)wordFile.FullName;
// Use the dummy value as a placeholder for optional arguments
Document doc = word.Documents.Open(ref filename, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing);
doc.Activate();
object outputFileName = wordFile.FullName.Replace(".doc", ".pdf");
object fileFormat = WdSaveFormat.wdFormatPDF;
// Save document into PDF Format
doc.SaveAs(ref outputFileName,
ref fileFormat, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing);
// Close the Word document, but leave the Word application open.
// doc has to be cast to type _Document so that it will find the
// correct Close method.
object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);
doc = null;
}
// word has to be cast to type _Application so that it will find
// the correct Quit method.
((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
word = null;
评论
适用于 word 的 Microsoft PDF 加载项似乎是目前最好的解决方案,但您应该考虑到它无法将所有 word 文档正确转换为 pdf,在某些情况下,您会看到 word 和输出 pdf 之间存在巨大差异。不幸的是,我找不到任何可以正确转换所有 word 文档的 api。 我发现确保转换 100% 正确的唯一解决方案是通过打印机驱动程序转换文档。缺点是文档被逐个排队和转换,但您可以确定生成的 pdf 与 word 文档布局完全相同。 我个人更喜欢使用 UDC(通用文档转换器)并在服务器上安装了 Foxit Reader(免费版),然后通过启动“进程”并将其 Verb 属性设置为“print”来打印文档。您还可以使用 FileSystemWatcher 在转换完成时设置信号。
总结一下 vb.net 用户,免费选项(必须安装 office):
Microsoft 办公组件下载:
- 适用于 Office 2010 的 PIA
添加对 Microsoft.Office.Interop.Word.Application 的引用
向 Microsoft.Office.Interop.Word.Application 添加 using 或 import (vb.net) 语句
VB.NET 示例:
Dim word As Application = New Application()
Dim doc As Document = word.Documents.Open("c:\document.docx")
doc.Activate()
doc.SaveAs2("c:\document.pdf", WdSaveFormat.wdFormatPDF)
doc.Close()
评论
当有人用 10000 个 word 文件转给我以转换为 PDF 时,我经历了 Word 到 PDF 的痛苦。现在我用 C# 做了它并使用了 Word 互操作,但如果我尝试使用 PC,它会很慢并且崩溃。非常令人沮丧。
这让我发现我可以抛弃互操作及其缓慢......对于我使用的 Excel(EPPLUS),然后我发现您可以获得一个名为 Spire 的免费工具,该工具允许转换为 PDF......有局限性!
http://www.e-iceblue.com/Introduce/free-doc-component.html#.VtAg4PmLRhE
评论
只是想补充一点,我使用了 Microsoft.Interop 库,特别是 ExportAsFixedFormat 函数,我没有看到在此线程中使用。
using Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;
using System.IO;
using Microsoft.Office.Core;
Application app;
public string CreatePDF(string path, string exportDir)
{
Application app = new Application();
app.DisplayAlerts = WdAlertLevel.wdAlertsNone;
app.Visible = true;
var objPresSet = app.Documents;
var objPres = objPresSet.Open(path, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);
var pdfFileName = Path.ChangeExtension(path, ".pdf");
var pdfPath = Path.Combine(exportDir, pdfFileName);
try
{
objPres.ExportAsFixedFormat(
pdfPath,
WdExportFormat.wdExportFormatPDF,
false,
WdExportOptimizeFor.wdExportOptimizeForPrint,
WdExportRange.wdExportAllDocument
);
}
catch
{
pdfPath = null;
}
finally
{
objPres.Close();
}
return pdfPath;
}
评论
app.Visible = false;
app.Quit();
使用 Microsoft.Office.Interop.Word
将 WORD 转换为 PDF 的简单代码和解决方案
using Word = Microsoft.Office.Interop.Word;
private void convertDOCtoPDF()
{
object misValue = System.Reflection.Missing.Value;
String PATH_APP_PDF = @"c:\..\MY_WORD_DOCUMENT.pdf"
var WORD = new Word.Application();
Word.Document doc = WORD.Documents.Open(@"c:\..\MY_WORD_DOCUMENT.docx");
doc.Activate();
doc.SaveAs2(@PATH_APP_PDF, Word.WdSaveFormat.wdFormatPDF, misValue, misValue, misValue,
misValue, misValue, misValue, misValue, misValue, misValue, misValue);
doc.Close();
WORD.Quit();
releaseObject(doc);
releaseObject(WORD);
}
添加以下过程以释放内存:
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
//TODO
}
finally
{
GC.Collect();
}
}
评论
pandoc manual.docx -o manual.pdf
docker "run" "--rm" "--entrypoint" "soffice" "-v" "$(pwd):/usr/src/project" "linuxserver/libreoffice:latest" "--headless" "--convert-to" "pdf" "--outdir" "/usr/src/project" "/usr/src/project/foo.docx"