【问题标题】:Convert a Word (DOCX) file to a PDF in C# on cloud environment在云环境中使用 C# 将 Word (DOCX) 文件转换为 PDF
【发布时间】:2015-09-11 11:08:39
【问题描述】:

我使用 Open Xml 生成了一个 word 文件,我需要将它作为附件发送到 pdf 格式的电子邮件中但我无法在磁盘上保存任何物理 pdf 或 word 文件,因为我正在开发我的应用程序在云环境中(CRM 在线)。

我发现唯一的方法是“Aspose Word to .Net”。 http://www.aspose.com/docs/display/wordsnet/How+to++Convert+a+Document+to+a+Byte+Array不过太贵了。

然后我找到了一个解决办法,就是先把word转成html,然后再把html转成pdf。但我的话里有一张照片。而且我无法解决问题。

【问题讨论】:

  • 很多像“Microsoft.Office.Interop.Word”这样的库都需要将物理文件保存到磁盘,所以字节数组的转换并不容易。

标签: c# pdf ms-word


【解决方案1】:

从 DOCX 到 PDF 的最准确转换是通过 Word。您最好的选择是使用OWAS(Office Web Apps Server)设置服务器并通过它进行转换。

您需要在应用服务器上设置WOPI 端点并调用:

/wv/WordViewer/request.pdf?WOPISrc={WopiUrl}&type=downloadpdf

/wv/WordViewer/request.pdf?WOPISrc={WopiUrl}&type=printpdf

您也可以尝试使用 OneDrive 和 Word Online 进行操作,但您需要确定 Word Online 使用的参数以及 Ts & Cs 中是否允许这样做。

【讨论】:

  • 我无法设置任何服务器。Word Online 可能是一个不错的解决方案。虽然它不是免费的。
  • 嗨@pmccloghrylaing!我需要实现一个 RESTful API 来准确地将 word 转换为 PDF,所以我想实现你提到的解决方案,在 Office Online Server 中设置一个 WOPI 端点。你有一些例子或提示可以帮助我完成我的任务吗?非常感谢!
【解决方案2】:

您可以尝试 Gnostice XtremeDocumentStudio .NET。

使用 XtremeDocumentStudio .NET 从 DOCX 转换为 PDF http://www.gnostice.com/goto.asp?id=24900&t=convert_docx_to_pdf_using_xdoc.net

在已发表的文章中,已演示转换以保存到物理文件。您可以使用 documentConverter.ConvertToStream 方法将文档转换为 Stream,如下面的代码 sn-p 所示。

DocumentConverter documentConverter = new DocumentConverter();
// input can be a FilePath, Stream, list of FilePaths or list of Streams
Object input = "InputDocument.docx";
string outputFileFormat = "pdf";
ConversionMode conversionMode = ConversionMode.ConvertToSeperateFiles;
List<Stream> outputStreams = documentConverter.ConvertToStream(input, outputFileFormat, conversionMode);

免责声明:我为 Gnostice 工作。

【讨论】:

    【解决方案3】:

    我最近在我的 React(前端)、.NET 核心(微服务-后端)应用程序中使用 SautinSoft 'Document .Net' 库将 docx 转换为 pdf。只需 15 秒即可生成 23 页的 pdf。这 15 秒包括从数据库中获取数据,然后将数据与 docx 模板合并,然后将其转换为 pdf。该代码已部署到 azure Linux box 并且运行良好。

    https://sautinsoft.com/products/document/

    示例代码

    public string GeneratePDF(PDFDocumentModel document)
            {
                byte[] output = null;
                using (var outputStream = new MemoryStream())
                {
                    // Create single pdf.
                    DocumentCore singlePDF = new DocumentCore();
    
                    var documentCores = new List<DocumentCore>();
                    foreach (var section in document.Sections)
                    {
                        documentCores.Add(GenerateDocument(section));
                    }
                    foreach (var dc in documentCores)
                    {
                        // Create import session.
                        ImportSession session = new ImportSession(dc, singlePDF, StyleImportingMode.KeepSourceFormatting);
    
                        // Loop through all sections in the source document.
                        foreach (Section sourceSection in dc.Sections)
                        {
                            // Because we are copying a section from one document to another,
                            // it is required to import the Section into the destination document.
                            // This adjusts any document-specific references to styles, bookmarks, etc.
                            // Importing a element creates a copy of the original element, but the copy
                            // is ready to be inserted into the destination document.
                            Section importedSection = singlePDF.Import<Section>(sourceSection, true, session);
    
                            // First section start from new page.
                            if (dc.Sections.IndexOf(sourceSection) == 0)
                                importedSection.PageSetup.SectionStart = SectionStart.NewPage;
    
                            // Now the new section can be appended to the destination document.
                            singlePDF.Sections.Add(importedSection);
    
                            //Paging 
                           
                            HeaderFooter footer = new HeaderFooter(singlePDF, HeaderFooterType.FooterDefault);
                            // Create a new paragraph to insert a page numbering.
                            // So that, our page numbering looks as: Page N of M.
                            Paragraph par = new Paragraph(singlePDF);
                            par.ParagraphFormat.Alignment = HorizontalAlignment.Center;
                            CharacterFormat cf = new CharacterFormat() { FontName = "Consolas", Size = 11.0 };
                            par.Content.Start.Insert("Page ", cf.Clone());
                            // Page numbering is a Field.
                            Field fPage = new Field(singlePDF, FieldType.Page);
                            fPage.CharacterFormat = cf.Clone();
                            par.Content.End.Insert(fPage.Content);
                            par.Content.End.Insert(" of ", cf.Clone());
                            Field fPages = new Field(singlePDF, FieldType.NumPages);
                            fPages.CharacterFormat = cf.Clone();
                            par.Content.End.Insert(fPages.Content);
                            footer.Blocks.Add(par);
    
                            importedSection.HeadersFooters.Add(footer);
                        }
                    }
    
                    var pdfOptions = new PdfSaveOptions();
                    pdfOptions.Compression = false;
                    pdfOptions.EmbedAllFonts = false;
                    pdfOptions.EmbeddedImagesFormat = PdfSaveOptions.EmbImagesFormat.Png;
                    pdfOptions.EmbeddedJpegQuality = 100;
    
                    //dont allow editing after population, also ensures content can be printed.
                    pdfOptions.PreserveFormFields = false;
                    pdfOptions.PreserveContentControls = false;
    
                    if (!string.IsNullOrEmpty(document.PdfProperties.Title))
                    {
                        singlePDF.Document.Properties.BuiltIn[BuiltInDocumentProperty.Title] = document.PdfProperties.Title;
                    }
    
        if (!string.IsNullOrEmpty(document.PdfProperties.Author))
        {
            singlePDF.Document.Properties.BuiltIn[BuiltInDocumentProperty.Author] = document.PdfProperties.Author;
        }
    
                    if (!string.IsNullOrEmpty(document.PdfProperties.Subject))
                    {
                        singlePDF.Document.Properties.BuiltIn[BuiltInDocumentProperty.Subject] = document.PdfProperties.Subject;
                    }                          
    
                    singlePDF.Save(outputStream, pdfOptions);
                    output = outputStream.ToArray();
                }
    
                return Convert.ToBase64String(output);
    
    
            }
    

    【讨论】:

    • 欢迎来到stackoverflow。如果您添加一个简短的代码示例会更好。
    猜你喜欢
    • 2016-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    相关资源
    最近更新 更多