编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

C# 用iTextSharp库来实现Word与PDF之间的互相转换

wxchong 2024-07-06 01:08:33 开源技术 11 ℃ 0 评论

#秋日生活打卡季#

iTextSharp是一个开源的.NET库,用于处理PDF文档。

可以使用iTextSharp库来实现Word文档与PDF格式之间的互相转换。

使用NuGet包管理器将iTextSharp库添加到您的项目中。

将Word文档转换为PDF:

using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

public void ConvertWordToPdf(string wordFilePath, string pdfFilePath)
{
    // Create a new PDF document
    Document pdfDocument = new Document();

    // Create a new PDF writer
    PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, new FileStream(pdfFilePath, FileMode.Create));

    // Open the PDF document
    pdfDocument.Open();

    // Create a new Word document
    var wordDocument = new Aspose.Words.Document(wordFilePath);

    // Iterate through the sections of the Word document
    foreach (var section in wordDocument.Sections)
    {
        // Create a new PDF page
        pdfDocument.NewPage();

        // Create a PDF content byte
        PdfContentByte pdfContentByte = pdfWriter.DirectContent;

        // Create a new PDF template
        PdfTemplate pdfTemplate = pdfContentByte.CreateTemplate(pdfDocument.PageSize.Width, pdfDocument.PageSize.Height);

        // Create a new graphics object from the PDF template
        Graphics2D graphics = new PdfGraphics2D(pdfTemplate, pdfDocument.PageSize.Width, pdfDocument.PageSize.Height);

        // Render the section's content to the PDF template
        section.RenderToSize(graphics, pdfDocument.PageSize.Width, pdfDocument.PageSize.Height);

        // Add the PDF template to the PDF content byte
        pdfContentByte.AddTemplate(pdfTemplate, 0, 0);
    }

    // Close the PDF document
    pdfDocument.Close();
}

将PDF转换为Word文档:

using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.IO;

public void ConvertPdfToWord(string pdfFilePath, string wordFilePath)
{
    // Create a new Word document
    var wordDocument = new Aspose.Words.Document();

    // Create a new PDF reader
    PdfReader pdfReader = new PdfReader(pdfFilePath);

    // Iterate through the pages of the PDF document
    for (int pageNumber = 1; pageNumber <= pdfReader.NumberOfPages; pageNumber++)
    {
        // Extract the text from the PDF page
        string pageText = PdfTextExtractor.GetTextFromPage(pdfReader, pageNumber);

        // Create a new paragraph in the Word document
        var paragraph = new Aspose.Words.Paragraph(wordDocument);

        // Add the extracted text to the paragraph
        paragraph.Append(pageText);

        // Add the paragraph to the Word document
        wordDocument.AppendChild(paragraph);
    }

    // Save the Word document
    wordDocument.Save(wordFilePath);
}

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表