C# Word和Pdf互相转换

整体命名空间:

using Spire.Pdf;
using System.IO;
using Word = Microsoft.Office.Interop.Word;

Word转Pdf

需要NuGet的包:Microsoft.Office.Interop.Word

public string WordToPdf(string wordPath, string pdfPath = null)
        {
            Word.Application application = new Word.Application();
            Word.Document document = null;

            application.Visible = false;
            document = application.Documents.Open(wordPath);
            pdfPath = pdfPath ?? wordPath.Replace(".docx", ".doc").Replace(".doc", ".pdf");

            int t = 1;
            while (File.Exists(pdfPath))
            {
                if (t == 1)
                {
                    pdfPath = string.Concat(Path.GetDirectoryName(pdfPath), "\\", Path.GetFileNameWithoutExtension(pdfPath), "(", t.ToString(), ").pdf");
                }
                else
                {
                    pdfPath = pdfPath.Replace("(" + (t - 1) + ").pdf", "(" + t + ").pdf");
                }
                t++;
            }

            if (!File.Exists(pdfPath))
            {
                document.ExportAsFixedFormat(pdfPath, Word.WdExportFormat.wdExportFormatPDF);
            }
            document.Close();
            return pdfPath;
        }

Pdf转Word

需要NuGet的包:Spire.Pdf

public string PdfToWord(string pdfPath, string wordPath = null)
        {
            PdfDocument document = new PdfDocument();
            document.LoadFromFile(pdfPath);

            wordPath = wordPath ?? pdfPath.Replace(".pdf", ".doc");

            int t = 1;
            while (File.Exists(pdfPath))
            {
                if (t == 1)
                {
                    pdfPath = string.Concat(Path.GetDirectoryName(pdfPath), "\\", Path.GetFileNameWithoutExtension(pdfPath), "(", t.ToString(), ").pdf");
                }
                else
                {
                    pdfPath = pdfPath.Replace("(" + (t - 1) + ").pdf", "(" + t + ").pdf");
                }
                t++;
            }

            if (!File.Exists(wordPath))
            {
                document.SaveToFile(wordPath, FileFormat.DOC);
            }
            document.Close();
            return wordPath;
        }

猜你喜欢

转载自blog.csdn.net/qq_41863100/article/details/103140109