C # export HTML to the PDF component Pechkin,
C # exporting PDF is a feature that is frequently encountered during development. We use third-party components, such as iTextSharp and aspose. We can also find some open-source class libraries,
However, for PDF with complex content and rich styles, we hope to generate a PDF directly by inputting a URL, and it cannot be too different from the original webpage version. Pechkin is good, but the difference is relatively small.
Search For "Pechkin" in the Nuget manager. Select CPechkin. net20 +, which was modified by the author based on Pechkin and removed Common. loging dependency. The description indicates that the project must be compiled on x86, but I found that only the Web project must be compiled on x86 (the IIS application pool seems to be set to x86). Otherwise, an error will be reported during running, windows Service, Windows Form project can default Any CPU
After the package is loaded, several DLL files will be placed under the project root directory, which are dependent on Pechkin. to delete these DLL files, copy them to the bin directory first.
After compilation, there are seven related DLL files in the BIN, which is all of the Pechkin files.
The call code is simple. You can do it in two lines. SetMargins sets the margins of the PDF file.
Pechkin.Synchronized.SynchronizedPechkin sc = new Pechkin.Synchronized.SynchronizedPechkin(new Pechkin.GlobalConfig().SetMargins(new System.Drawing.Printing.Margins(20, 20, 20, 20)));byte[] buf = sc.Convert(new Uri(previewUrl));
var ms = new System.IO.MemoryStream(buf);var fn = string.Format("report_{0}.pdf", reportNo);Logger.Instance.WriteLine("Generate a pdf from url {0}", previewUrl);return new List<System.Net.Mail.Attachment> { new System.Net.Mail.Attachment(ms, fn, "application/pdf") };
After obtaining a byte [], you can write a file to generate a PDF file. I write a MemoryStream in the code, and then add an attachment to the email for sending, which is very convenient.
Pechkin also supports inputting an HTML code to generate a PDF file.
Let's look at the generated PDF, which is the PDF on the left and the original webpage on the right. The difference is not big, that is, the background color of the table is lost.