我如何在c#中将word文件(.docx & doc
)转换为.pdf
,而不使用SaveAs()
或Save()
方法?或者不上传到服务器?
我如何在c#中将word文件(.docx & doc
)转换为.pdf
,而不使用SaveAs()
或Save()
方法?或者不上传到服务器?
你可以试试这个,我用过了觉得很有效:
using Microsoft.Office.Interop.Word;
var appWord = new Application();
if (appWord.Documents != null)
{
//yourDoc is your word document
var wordDocument = appWord.Documents.Open(yourDoc);
string pdfDocName = "pdfDocument.pdf";
if (wordDocument != null)
{
wordDocument.ExportAsFixedFormat(pdfDocName,
WdExportFormat.wdExportFormatPDF);
wordDocument.Close();
}
appWord.Quit();
}
using
块来杀死实例,繁忙的站点也可能同时启动10或20个Word实例。 - Panagiotis Kanavos如果您能购买许可证,Aspose.Words 是处理此类任务的非常好的解决方案。免费版本会向输出PDF添加警告消息。
如果您正在寻找免费的解决方案,则可以使用FreeSpire.Doc。 免费版本有以下限制:
免费版仅限500个段落和25个表格。当读取或写入文件时将强制执行此限制。将 Word 文档转换为 PDF 和 XPS 文件时,您只能获取前3页的 PDF 文件。请升级到Spire.Doc商业版。
不需要使用 MS Office、Office.Interop 或 Office自动化。
通过 NuGet 安装:
Install-Package FreeSpire.Doc -Version 7.11.0
代码示例:
using System;
using Spire.Doc;
using Spire.Doc.Documents;
namespace DoctoPDF
{
class toPDF
{
static void Main(string[] args)
{
//Load Document
Document document = new Document();
document.LoadFromFile(@"E:\work\documents\TestSample.docx");
//Convert Word to PDF
document.SaveToFile("toPDF.PDF", FileFormat.PDF);
//Launch Document
System.Diagnostics.Process.Start("toPDF.PDF");
}
}
}
如果您的计算机上安装了 MS Office Word,则无需进行任何额外的编译器配置,可以尝试以下方法:
using System;
using System.IO;
using System.Reflection;
namespace KUtil
{
public class Word2PDF
{
static void Main(string[] args)
{
var word = Type.GetTypeFromProgID("word.application");
dynamic app = Activator.CreateInstance(word);
if (args.Length < 1)
{
return;
}
var path = args[0];
var outPath = Path.ChangeExtension(path, "pdf");
dynamic doc = app.Documents.Open(path);
doc.ExportAsFixedFormat(outPath,
ExportFormat:17/*pdf*/);
doc.Close(0/*DoNotSaveChanges*/);
app.Quit();
}
}
}
using Spire.Doc;
namespace ToPDF
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document document = new Document();
//Load a sample Word document
document.LoadFromFile(@"C:\Users\Administrator\Desktop\Test.docx");
//Save the document to PDF
document.SaveToFile("ToPDF.pdf", FileFormat.PDF);
}
}
}
您可以使用这段代码来使用Aspose将MS Word文档转换为PDF格式
public class Program
{
public static void Main(string[] args)
{
var content = File.ReadAllBytes("response.doc");
var document = new Document(new MemoryStream(content));
ClearFormat(document);
var options = SaveOptions.CreateSaveOptions(SaveFormat.Pdf);
options.PrettyFormat = true;
options.UseAntiAliasing = true;
options.UseHighQualityRendering = true;
document.Save("response.pdf", options);
}
private static void ClearFormat(Document doc)
{
for (var i = 0; i < doc.Sections.Count; i++)
{
var nodes = doc.Sections[i].GetChildNodes(NodeType.Run, true);
if (nodes == null || nodes.Count <= 0) continue;
foreach (var item in (from Run item in nodes
where item.Font.Name.ToLower().Contains("nastaliq")
select item).ToList())
{
item.Font.Name = "Times New Roman";
item.Font.Size = item.Font.Size > 12 ? 12 : item.Font.Size;
}
}
}
}
using System.Diagnostics;
namespace ConvertDOCXToPDF
{
internal class Program
{
static void Main(string[] args)
{
// Create LibreOfficeWriter CLI process
var commandArgs = new List<string>
{
"--convert-to", //a flag that will be followed by the file type we want to convert to
"pdf:writer_pdf_Export", // the [output file type]:[OutputFilterName] we are requesting the output to be; more details are here (https://help.libreoffice.org/latest/en-US/text/shared/guide/convertfilters.html)
"C:\\Users\\zachary\\Downloads\\Letter.docx", // input file
"--norestore", // disables restart and file recovery after a system crash
"--headless", // allows using the application without user interface
"--outdir", // a flag that will be followed by the output directory where we want our new pdf file to be created
"C:\\Users\\zachary\\Downloads" // output directory
};
// The path to LibreOfficeWriterPortable.exe
ProcessStartInfo processStartInfo = new ProcessStartInfo("C:\\Users\\zachary\\Downloads\\LibreOfficePortablePrevious\\LibreOfficeWriterPortable.exe");
foreach (string arg in commandArgs)
processStartInfo.ArgumentList.Add(arg);
Process process = new Process
{
StartInfo = processStartInfo
};
// Only 1 instance of LibreOfficeWriter can be running at a given time
Process[] existingProcesses = Process.GetProcessesByName("soffice");
while (existingProcesses.Length > 0)
{
Thread.Sleep(1000);
existingProcesses = Process.GetProcessesByName("soffice");
}
// Start the process
process.Start();
process.WaitForExit();
// Check for failed exit code.
if (process.ExitCode != 0)
throw new Exception("Failed to convert file");
else
{
int totalChecks = 10;
int currentCheck = 1;
string originalFileName = Path.GetFileNameWithoutExtension(commandArgs[2]);
string newFilePath = Path.Combine(commandArgs[6], $"{originalFileName}.pdf");
while (currentCheck <= totalChecks)
{
if (File.Exists(newFilePath))
{
// File conversion was successful
break;
}
Thread.Sleep(500); // LibreOffice doesn't immediately create PDF output once the command is run
}
}
}
}
}
根据wangkaibule的回答,可以使用标题书签进行PDF转换。它也适用于.NET 7(类似于链接的帖子)。
public static void Convert(string inputFileName, string outputFileName)
{
// Microsoft.Office.Interop.Word.WdSaveFormat enum
const int wdFormatPDF = 17;
// Microsoft.Office.Interop.Word.WdExportCreateBookmarks enum
const int wdExportCreateHeadingBookmarks = 1;
// Microsoft.Office.Interop.Word.WdSaveOptions enum
const int wdDoNotSaveChanges = 0;
var word = Type.GetTypeFromProgID("word.application");
if (word == null)
{
throw new ArgumentException("Microsoft Word is not installed on the system.");
}
dynamic app = Activator.CreateInstance(word);
try
{
dynamic doc = app.Documents.Open(inputFileName);
doc.ExportAsFixedFormat(outputFileName, ExportFormat: wdFormatPDF, CreateBookmarks: wdExportCreateHeadingBookmarks);
doc.Close(wdDoNotSaveChanges);
}
finally
{
app.Quit();
}
}