如何将多个网页转换为一个pdf文档?

时间:2012-07-19 15:29:15

标签: c# asp.net

public FileResult Download() 
{ 

    var doc = new EO.Pdf.PdfDocument(); 
    EO.Pdf.HtmlToPdf.ConvertUrl("http://www.google.com/", doc); 

    var ms = new MemoryStream();     
    doc.Save(ms); 

    ms.Position = 0; 

    return new FileStreamResult(ms, "application/pdf") 
               { 
                   FileDownloadName = "download.pdf"
               }; 
}

如果可能的话,请您展示如何扩展上面的代码,以便能够将多个网页转换成一个pdf文档?

棘手的部分是我们不知道用户可能尝试转换的页面。

因此,如上面的代码所示,对网页进行硬编码并没有帮助我们。

非常感谢任何帮助。

//Create a new PdfDocument object
var doc = new EO.Pdf.PdfDocument();

//Convert two ore more different pages into the same PdfDocument

EO.Pdf.HtmlToPdf.ConvertUrl("c:\\1.html", doc);

EO.Pdf.HtmlToPdf.ConvertUrl("c:\\2.html", doc);

最新代码:

public FileResult Download() 
{ 
    var doc = new EO.Pdf.PdfDocument(); 

foreach(var url in passedUrls)  
{ 
EO.Pdf.HtmlToPdf.ConvertUrl(url, doc);   
doc.Save(ms);   
}


    ms.Position = 0; 

    return new FileStreamResult(ms, "application/pdf") 
               { 
                   FileDownloadName = "download.pdf"
               }; 
}

Adam的最新消息(谢谢先生)

public FileResult Download() 
{ 

var documents = new List<EO.Pdf.PdfDocument>(); 
foreach(var url in passedUrls) 
{ 
    var doc = new EO.Pdf.PdfDocument(); 
    EO.Pdf.HtmlToPdf.ConvertUrl(url, doc); 
    documents.Add(doc); 
} 

EO.Pdf.PdfDocument mergedDocument = EO.Pdf.PdfDocument.Merge(documents.ToArray()); 
}

希望其他人认为这些代码很有用。

2 个答案:

答案 0 :(得分:2)

基于Help documentation,我建议如下:

public FileResult Download()
{
    var urls = new List<string>
    { // Populate list with urls
        "C:\\1.html",
        "C:\\2.html"
    };

    var documents = new List<EO.Pdf.PdfDocument>();
    foreach(var url in urls)
    {
        var doc = new EO.Pdf.PdfDocument();
        EO.Pdf.HtmlToPdf.ConvertUrl(url, doc);
        documents.Add(doc);
    }

    EO.Pdf.PdfDocument mergedDocument = EO.Pdf.PdfDocument.Merge(documents.ToArray());

    var ms = new MemoryStream();
    mergedDocument.Save(ms);
    ms.Position = 0;

    return new FileStreamResult(ms, "application/pdf") { FileDownloadName = "download.pdf" };
}

答案 1 :(得分:1)

将一组url字符串传递给函数

然后

foreach(var url in passedUrls) 
{
EO.Pdf.HtmlToPdf.ConvertUrl(url, doc);  
doc.Save(ms);  
}