【发布时间】:2016-11-20 17:13:18
【问题描述】:
如何在不使用SaveAs() 或Save() 方法的情况下将c# 中的word 文件(.docx & doc)转换为.pdf?还是不上传到服务器?
【问题讨论】:
标签: c#
如何在不使用SaveAs() 或Save() 方法的情况下将c# 中的word 文件(.docx & doc)转换为.pdf?还是不上传到服务器?
【问题讨论】:
标签: c#
试试这个,它对我有用:
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 实例
如果您可以购买许可证,Aspose.Words 是非常好的解决方案。免费版在输出 PDF 中添加警告消息。
如果您正在寻找免费的东西,我使用了 FreeSpire.Doc,免费版本有以下限制:
免费版限制为 500 个段落和 25 个表格。此限制在读取或写入文件期间强制执行。将word文档转换为PDF和XPS文件时,只能得到PDF文件的前3页。升级到 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();
}
}
}
【讨论】:
您可以使用此代码使用 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;
}
}
}
}
【讨论】: