Convert HTML to PDF - pdfsharp

Asked

Viewed 154 times

0

I am with another question now, I am trying to use Pdfsharp Htmlrenderer, to generate a pdf, to send by email. I downloaded the nuget package, and function is like this:

 public static Byte[] PdfSharpConvert(String html)
    {
        Byte[] res = null;
        using (MemoryStream ms = new MemoryStream())
        {
            var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.A4);
            pdf.Save(ms);
            res = ms.ToArray();
        }
        return res;
    }

What happens, all my items I need to be generated PDF, is generated in a div on the front. I wanted to pass this information from the front to the back, so that the PDF is generated, is it possible ? I don’t even necessarily need to save this pdf, it might be something temporary, to send by email. I’m a little lost in the Pdfsharp library, I’m reading the documents but I’m more confused rs.

1 answer

1


Hi, I saw that you are also using Angularjs, so I believe it is better to generate the pdf with the own angular and after that send it as already ready file to the Backend and so save and send by email.

Use these libraries.

import * as jspdf from 'jspdf';  

import html2canvas from 'html2canvas';

create a button or something to copy the div:

<input type="button" value="PDF" (click)="captureScreen()"/>  

and after that generates the PDF:

export class HtmltopdfComponent{  
  public captureScreen()  
  {  
     var data = document.getElementById('sua div para converter');  
     html2canvas(data).then(canvas => {  
     var imgWidth = 208;   
     var pageHeight = 295;    
     var imgHeight = canvas.height * imgWidth / canvas.width;  
     var heightLeft = imgHeight;  

     const contentDataURL = canvas.toDataURL('image/png')  
     let pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF  
     var position = 0;  
     pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)  
     pdf.save('MYPdf.pdf'); // Generated PDF   
    });  
  }  
}  
  • I did the test here @Matheus, but it only comes out a sheet, and will have cases that will take more than one sheet, and also this div was with style="display: none;", and then returned error, I had to take to be able to generate, and yet it was not the right way

  • Can you post an example of how you needed it and how you’re doing ?

  • Matheus managed to make it work, but I will not use this option, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.