【问题标题】:HTML Renderer/PDFsharp Combine Two HTML-Generated PDF DocumentsHTML Renderer/PDFsharp 合并两个 HTML 生成的 PDF 文档
【发布时间】:2018-08-06 00:32:41
【问题描述】:

我正在尝试在一个文档中添加两页。这两个页面是从 HTML 生成的。

信息:使用 PDFsharp 的 HTML 渲染器,HtmlRenderer.PdfSharp 1.5.0.6

            var config = new PdfGenerateConfig
        {
            PageOrientation = PageOrientation.Portrait,
            PageSize = PageSize.A4,
            MarginBottom = 0,
            MarginLeft = 0,
            MarginRight = 0,
            MarginTop = 0
        };
            string pdfFirstPage = CreateHtml();
            string pdfsecondPage = CreateHtml2();   
            PdfDocument doc=new PdfDocument();
            doc.AddPage(new PdfPage(PdfGenerator.GeneratePdf(pdfFirstPage, config)));
            doc.AddPage(new PdfPage(PdfGenerator.GeneratePdf(pdfsecondPage, config)));

我尝试了几种方法,但最常见的错误是导入模式。这是最后一次测试,但没有成功。如何将 HTML 字符串生成的两个页面合并为 1 个文档中的 2 个页面并下载?

【问题讨论】:

    标签: c# asp.net pdfsharp html-renderer


    【解决方案1】:

    这是有效的代码:

    static void Main(string[] args)
    {
        PdfDocument pdf1 = PdfGenerator.GeneratePdf("<p><h1>Hello World</h1>This is html rendered text #1</p>", PageSize.A4);
        PdfDocument pdf2 = PdfGenerator.GeneratePdf("<p><h1>Hello World</h1>This is html rendered text #2</p>", PageSize.A4);
    
        PdfDocument pdf1ForImport = ImportPdfDocument(pdf1);
        PdfDocument pdf2ForImport = ImportPdfDocument(pdf2);
    
        var combinedPdf = new PdfDocument();
    
        combinedPdf.Pages.Add(pdf1ForImport.Pages[0]);
        combinedPdf.Pages.Add(pdf2ForImport.Pages[0]);
    
        combinedPdf.Save("document.pdf");
    }
    
    private static PdfDocument ImportPdfDocument(PdfDocument pdf1)
    {
        using (var stream = new MemoryStream())
        {
            pdf1.Save(stream, false);
            stream.Position = 0;
            var result = PdfReader.Open(stream, PdfDocumentOpenMode.Import);
            return result;
        }
    }
    

    我将 PDF 文档保存到 MemoryStream 并打开它们进行导入。这允许将页面添加到新的PdfDocument。为简单起见,仅使用文档的第一页 - 根据需要添加循环。

    【讨论】:

    • 首先感谢您的回答。我试过第一个不起作用。第二个抛出异常并在此处说明“已添加具有相同密钥的项目”。保存(ms2, false);.我认为这是关于 PdfDictionary 因为克隆返回 PdfDictionary
    • 你是伟大的努力之王。我很感谢你 :)
    猜你喜欢
    • 2011-11-27
    • 1970-01-01
    • 2019-10-01
    • 2016-08-24
    • 1970-01-01
    • 2015-12-21
    • 2022-01-05
    • 1970-01-01
    • 2013-06-05
    相关资源
    最近更新 更多