使用C#将PDF文档转换为DOCX文档

博客类别:PDF办公.NET

2024/04/12

PDF 文档是一种包含文档元素固定布局的完整描述的文档,这些元素包括文本、字体、图形以及显示文档所需的其他信息。PDF 文档的优点在于,无论使用何种设备,其显示效果始终保持一致。PDF 文档的另一个优点是,每页的内容都是单独存储的,例如,您可以渲染并查看 1000 页 PDF 文档的最后一页,而无需渲染该文档的所有其他页面。PDF 文档的缺点是编辑其内容较为困难。

DOCX 文档是一种 Microsoft Word Open XML 格式的文档,其中包含文本、图像、图形等。DOCX 文档的优点是其内容编辑简单直观。DOCX 文档的缺点是需要对文档内容进行布局才能将其分成多个页面。换句话说,对于一份 1000 页的 DOCX 文档,即使您只需要查看最后一页,也需要渲染文档的所有页面。

基于上述优缺点,PDF 文件便于查看和存储文档,而 DOCX 文件便于创建和编辑文档。

VintaSoft Imaging .NET SDK 允许编辑 PDF 文档的内容,您可以在这里阅读相关信息。

此外,VintaSoft Imaging .NET SDK 允许将 PDF 文档转换为 DOCX 文档,以便在适当的文本编辑器程序(例如 MicrosoftOffice Word 或 OpenOffice Writer)中进一步编辑 DOCX 文档。

VintaSoft Imaging .NET SDK 也允许将 DOCX 文档转换回 PDF 文档。

以下是 C# 代码,可将 PDF 文档转换为 DOCX 文档:
/// <summary>
/// Converts PDF document to a DOCX document.
/// </summary>
public static void ConvertPdfToDocx(string pdfFileName, string docxFileName)
{
    // create an image collection
    using (Vintasoft.Imaging.ImageCollection imageCollection = new Vintasoft.Imaging.ImageCollection())
    {
        // add PDF document to the image collection
        imageCollection.Add(pdfFileName);

        // save images of image collection (PDF pages) to a DOCX file
        imageCollection.SaveSync(docxFileName);

        // dispose images
        imageCollection.ClearAndDisposeItems();
    }
}

以下是 C# 代码,可将 DOCX 文档转换为 PDF 文档:
/// <summary>
/// Converts DOCX document to a PDF document.
/// </summary>
public static void ConvertDocxToPdf(string docxFileName, string pdfFileName)
{
    // create an image collection
    using (Vintasoft.Imaging.ImageCollection imageCollection = new Vintasoft.Imaging.ImageCollection())
    {
        // add DOCX document to the image collection
        imageCollection.Add(docxFileName);

        // create PdfEncoder
        using (Vintasoft.Imaging.Codecs.Encoders.PdfEncoder pdfEncoder = 
            new Vintasoft.Imaging.Codecs.Encoders.PdfEncoder(true))
        {
            // set compression for image resources in PDF document
            pdfEncoder.Settings.Compression = Vintasoft.Imaging.Codecs.Encoders.PdfImageCompression.Jpeg;

            // save images of image collection (DOCX pages) to a PDF document
            imageCollection.SaveSync(pdfFileName, pdfEncoder);
        }

        // dispose images
        imageCollection.ClearAndDisposeItems();
    }
}