简体   繁体   中英

ASP.NET converting HTML to PDF

I have tried multiple plugins and c# classes to try and convert the HTML and CSS on my asp.net project to a pdf and even though the code used looks fine, and the button click works for other functions, I just cannot seem to get any html to pdf function to work. Has anyone else encountered this, or know if there is something I have missed to resolve it?

This is the latest code I have tried for hiqpdf in C#:

protected void Print_Button_Click(object sender, EventArgs e)
{


    HtmlToPdf htmlToPdfConverter = new HtmlToPdf();

    // set PDF page size, orientation and margins
    htmlToPdfConverter.Document.PageSize = PdfPageSize.A4;
    htmlToPdfConverter.Document.PageOrientation = PdfPageOrientation.Portrait;
    htmlToPdfConverter.Document.Margins = new PdfMargins(0);

    // convert HTML to PDF 
    htmlToPdfConverter.ConvertUrlToFile("http://localhost:51091/Printout","mcn.pdf");


}

It is not stated directly within theHiQpdf documentation of the method, but the method ConvertUrlToFile() stores the produced pdf file locally on the disc. On some example page (Convert URLs and HTML Code to PDF) the following comment can be found:

        // ConvertUrlToFile() is called to convert the html document and save the resulted PDF into a file on disk
        // Alternatively, ConvertUrlToMemory() can be called to save the resulted PDF in a buffer in memory
        htmlToPdfConverter.ConvertUrlToFile(url, pdfFile);

Since your example shows a button-click eventhandler, the file is probably generated but not used to return in the http response. You have to write the data into the response. The methods ConvertToStream() or ConvertToMemory should come in handy to do so. Don't forget to use Response.Clear() or Response.ClearContent() and Response.ClearHeader() before that and Flush() and Close() afterwards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM