private byte[] ExportLetterToPdf(string html) { //recomend to use Pechkin.Synhrozine for generating pdf from html //recomend to use Pechkin.Synhrozine for generating pdf from html // byte[] bytes = new SimplePechkin(new GlobalConfig()).Convert(html); //IPechkin pechkin = new SynchronizedPechkin(new GlobalConfig()); //byte[] bytes = pechkin.Convert(html); byte[] bytes; using (MemoryStream ms = new MemoryStream()) { var config = new PdfGenerateConfig(); config.PageSize = PageSize.Letter; // config.PageSize = PageSize.A4; //todo: load margins from letter user settings for pdf config.MarginLeft = 20; config.MarginRight = 20; config.MarginTop = 25; config.MarginBottom = 25; using (var pdf = PdfGenerator.GeneratePdf(html, config)) { if (pdf.PageCount == 0) { pdf.Close(); bytes = new byte[0]; return(bytes); } pdf.Save(ms, false); bytes = ms.ToArray(); } } return(bytes); }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected virtual void exportAsPDFMenuItem_Click(object sender, EventArgs e) { //Save! SaveFileDialog saveFileDialog = new SaveFileDialog(); //Default name of the file is the editor file name saveFileDialog.FileName = Path.GetFileNameWithoutExtension(this.FileInfo.FileName) + ".pdf"; //The current path saveFileDialog.InitialDirectory = this.markdownViewer.Notepad.GetCurrentDirectory(); // saveFileDialog.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*"; // if (saveFileDialog.ShowDialog() == DialogResult.OK) { //Build a config based on made settings PdfGenerateConfig pdfConfig = new PdfGenerateConfig(); pdfConfig.PageOrientation = this.markdownViewer.Options.pdfOrientation; pdfConfig.PageSize = this.markdownViewer.Options.pdfPageSize; //Set margins int[] margins = this.markdownViewer.Options.GetMargins(); pdfConfig.MarginLeft = MilimiterToPoint(margins[0]); pdfConfig.MarginTop = MilimiterToPoint(margins[1]); pdfConfig.MarginRight = MilimiterToPoint(margins[2]); pdfConfig.MarginBottom = MilimiterToPoint(margins[3]); //Generate PDF and save PdfDocument pdf = PdfGenerator.GeneratePdf(BuildHtml(ConvertedText, this.FileInfo.FileName), pdfConfig, PdfGenerator.ParseStyleSheet(this.getCSS())); pdf.Save(saveFileDialog.FileName); //Open if requested if (this.markdownViewer.Options.pdfOpenExport) { Process.Start(saveFileDialog.FileName); } } }
/// <summary> /// Create PDF using PdfSharp project, save to file and open that file. /// </summary> private void OnGeneratePdf_Click(object sender, EventArgs e) { string outPDFPath = @"C:\Users\tmi\Downloads\obnova_kulturnych_pamiatok.1.0 (2)TMI (2).pdf"; string htmlstring = generateHtml(); if (!string.IsNullOrEmpty(htmlstring)) { PdfGenerateConfig x = new PdfGenerateConfig(); x.EnablePageNumbering = true; x.PageNumbersFont = new XFont("Times New Roman", 11); x.PageNumbersPattern = "{0}/{1}"; x.PageNumberLocation = PageNumberLocation.Middle; x.PageNumbersMarginBottom = 20; x.PageNumbersLeftRightMargin = 10; x.PageSize = PageSize.A4; x.SetMargins(30); var pdf = PdfGenerator.GeneratePdf(htmlstring, x, null, null, null); using (FileStream fs = new FileStream(outPDFPath, FileMode.Create)) { pdf.Save(fs, true); } System.Diagnostics.Process.Start(outPDFPath); } }
internal override void Render() { RenderFilling(); HtmlFormFormatInfo formatInfo = (HtmlFormFormatInfo)_renderInfo.FormatInfo; Area contentArea = _renderInfo.LayoutInfo.ContentArea; XRect destRect = new XRect(contentArea.X, contentArea.Y, formatInfo.Width, formatInfo.Height); if (formatInfo.Failure == HtmlFormFailure.None) { XImage xImage = null; try { // TODO: Falhar com _form.Content vazio // TODO: Add CropX, CropY, etc... XRect srcRect = new XRect(0, 0, formatInfo.Width, formatInfo.Height); var config = new PdfGenerateConfig { ManualPageSize = new XSize(formatInfo.Width, formatInfo.Height), MarginBottom = 0, MarginTop = 0, MarginLeft = 0, MarginRight = 0 }; using (var htmlPdfDoc = PdfGenerator.GeneratePdf(_form.Content, config)) { using (var pdfStream = new MemoryStream()) { htmlPdfDoc.Save(pdfStream); xImage = XPdfForm.FromStream(pdfStream); _gfx.DrawImage(xImage, destRect, srcRect, XGraphicsUnit.Point); } } } catch (Exception) { RenderFailureImage(destRect); } finally { if (xImage != null) { xImage.Dispose(); } } } else { RenderFailureImage(destRect); } RenderLine(); }
private PdfDocument GeneratePDF(string[] data) { PdfDocument pdf = new PdfDocument(); PdfGenerateConfig PGC = new PdfGenerateConfig(); PGC.PageSize = PdfSharp.PageSize.A4; PGC.PageOrientation = PdfSharp.PageOrientation.Landscape; pdf = PdfGenerator.GeneratePdf(throwTicketCode(data), PGC); return(pdf); }
public static void GenerarPDFCEO(List <string> ListHtml, string pathImgHeader, string pathImgFooter, string pathPDF, double pageSizeHeigth, double pageSizeWidth) { try { PdfGenerateConfig config = new PdfGenerateConfig(); config.PageSize = PageSize.Undefined; config.ManualPageSize = new XSize(pageSizeWidth, pageSizeHeigth); //config.ManualPageSize.Height = pageSizeHeigth; //config.ManualPageSize.Width = pageSizeWidth; //config.SetMargins(30); config.MarginLeft = 15; config.MarginRight = 15; config.MarginBottom = 30; config.MarginTop = 30; //string html = File.ReadAllText("C:\\Users\\k697344\\Documents\\Comex PPG\\Documentacion\\Ejemplo_3.html"); //var doc = PdfGenerator.GeneratePdf(html, config); var doc = new PdfDocument(); foreach (string html in ListHtml) { PdfGenerator.AddPdfPages(doc, html, config); double h = doc.Pages.Cast <PdfPage>().Last().Height.Value; double w = doc.Pages.Cast <PdfPage>().Last().Width.Value; XGraphics graph = XGraphics.FromPdfPage(doc.Pages.Cast <PdfPage>().Last()); //string pathImgHeader = "C:\\Users\\k697344\\Documents\\Comex PPG\\Documentacion\\header.png"; XImage xImageHeader = XImage.FromFile(pathImgHeader); graph.DrawImage(xImageHeader, 0, 0, w - 10, 20); //string pathImgFooter = "C:\\Users\\k697344\\Documents\\Comex PPG\\Documentacion\\footer.png"; XImage xImageFooter = XImage.FromFile(pathImgFooter); graph.DrawImage(xImageFooter, 10, h - 20, w - 10, 20); } //var tmpFile = Path.GetTempFileName(); //tmpFile = Path.GetFileNameWithoutExtension(tmpFile) + ".pdf"; doc.Save(pathPDF); } catch (Exception ex) { throw ex; } }
private PdfDocument getPdfDocFrom(string htmlString) { PdfGenerateConfig config = new PdfGenerateConfig(); config.PageOrientation = PdfSharp.PageOrientation.Portrait; config.PageSize = PdfSharp.PageSize.A4; PdfDocument doc = PdfGenerator.GeneratePdf(htmlString, config); return(doc); }
public void GeneratePdf_ValidHtmlContent_ReturnPdfDocument() { const string htmlContent = @" <!DOCTYPE html> <html lang=""en""> <head> <meta charset=""UTF-8""> <link rel=""Stylesheet"" href=""StyleSheet"" /> <title>F#</title> </head> <body> <h1>F Sharp (programming language) ภาษา F#</h1> <p> F# is a mature, open source, cross-platform, functional-first programming language. It empowers users and organizations to tackle complex computing problems with simple, maintainable and robust code. </p> </body> </html>"; /* * By default, A runtime throws a NotSupportedException * "No data is available for encoding 1252." on .NET Core. * To fix, add a dependency to the package System.Text.Encoding.CodePages * and then add code to register the code page provider during application initialization (f.ex in Startup.cs): * * System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); * This is required to parse strings in binary BIFF2-5 Excel documents encoded with DOS-era code pages. * These encodings are registered by default in the full .NET Framework, but not on .NET Core. */ Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); var config = new PdfGenerateConfig { PageSize = PageSize.A4 }; config.SetMargins(20); var document = PdfGenerator.GeneratePdf( htmlContent, config, null, OnStylesheetLoad, OnImageLoadPdfSharp ); var tempFile = Path.GetFileNameWithoutExtension( $"{Path.GetTempFileName()}.pdf" ); document.Save(tempFile); }
public static Byte[] PdfSharpConvert(String html) { Byte[] res = null; using (MemoryStream ms = new MemoryStream()) { PdfGenerateConfig config = new PdfGenerateConfig(); config.PageSize = PageSize.A4; config.SetMargins(20); var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(html, config, null, PdfUtils.OnStylesheetLoad); pdf.Save(ms); res = ms.ToArray(); } return(res); }
/// <summary> /// Create PDF using PdfSharp project, save to file and open that file. /// </summary> private void OnGeneratePdf_Click(object sender, EventArgs e) { PdfGenerateConfig config = new PdfGenerateConfig(); config.PageSize = PageSize.A4; config.SetMargins(20); var doc = PdfGenerator.GeneratePdf(_mainControl.GetHtml(), config, null, DemoUtils.OnStylesheetLoad, HtmlRenderingHelper.OnImageLoadPdfSharp); var tmpFile = Path.GetTempFileName(); tmpFile = Path.GetFileNameWithoutExtension(tmpFile) + ".pdf"; doc.Save(tmpFile); Process.Start(tmpFile); }
public static PdfDocument GeneratePdfByHtml(this string html, PdfSharp.PageSize pageSize = PdfSharp.PageSize.A4, int MarginBottom = 70, int MarginLeft = 20, int MarginRight = 20, int MarginTop = 70, string css = "") { var config = new PdfGenerateConfig() { MarginBottom = MarginBottom, MarginLeft = MarginLeft, MarginRight = MarginRight, MarginTop = MarginTop, PageSize = pageSize }; var Css = PdfGenerator.ParseStyleSheet(css); return(PdfGenerator.GeneratePdf(html, config, Css)); }
public static string generaPDF(int tipo, int idArticulo) { string estado = "0"; try { int idUsuario = Int32.Parse(HttpContext.Current.Session["idUsuario"].ToString()); DataTable dt = metodo.WSConsultarArticuloxId(idArticulo, idUsuario).Tables[0]; string contenido = dt.Rows[0][2].ToString(); string tituloArticulo = dt.Rows[0][1].ToString(); string fecha = DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss"); fecha = fecha.Replace(" ", "_"); fecha = fecha.Replace(":", "_"); fecha = fecha.Replace("-", "_"); //Se genera PDF //var Renderer = new IronPdf.HtmlToPdf(); //var PDF = Renderer.RenderHtmlAsPdf(contenido); PdfSharp.Pdf.PdfDocument pdf = PdfGenerator.GeneratePdf("<h3>" + tituloArticulo + "</h3>" + contenido, PdfSharp.PageSize.A4, 65); var config = new PdfGenerateConfig() { MarginBottom = 70, MarginLeft = 20, MarginRight = 20, MarginTop = 70, }; string OutputPath = HttpContext.Current.Server.MapPath("~/SUPPORTCENTERPDF/" + tituloArticulo + fecha + ".pdf"); pdf.Save(OutputPath); if (tipo == 1) { estado = "../SUPPORTCENTERPDF/" + tituloArticulo + fecha + ".pdf"; } else { estado = OutputPath; } } catch (Exception exp) { estado = "3"; } return(estado); }
/// <summary> /// Create PDF using PdfSharp project, save to file and open that file. /// </summary> private async Task OnGeneratePdf_Click(object sender, EventArgs e) { PdfGenerateConfig config = new PdfGenerateConfig(); config.PageSize = PageSize.A4; config.SetMargins(20); var doc = await PdfGenerator.GeneratePdf(_resourceServer, config); var tmpFile = Path.GetTempFileName(); tmpFile = Path.GetFileNameWithoutExtension(tmpFile) + ".pdf"; doc.Save(tmpFile); Process.Start(tmpFile); }
public static Stream ToPDF(this HtmlAgilityPack.HtmlDocument htmlDocument) { var config = new PdfGenerateConfig { PageSize = PdfSharp.PageSize.A4 }; config.SetMargins(20); PdfDocument doc = PdfGenerator.GeneratePdf(htmlDocument.ParsedText, config); var output = new MemoryStream(); doc.Save(output); return(output); }
public ActionResult Download(FormCollection fc) { //start the tier to measure the download time System.Diagnostics.Stopwatch downloadTimer = new System.Diagnostics.Stopwatch(); downloadTimer.Start(); StringBuilder HTMLstring = new StringBuilder("<html><head></head><body><h1>Example PDF page. Spinner in ASP.NET MVC. thoughtsonprogramming.wordpress.com</h1></body></html>"); Response.Clear(); Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=" + "PDFfile.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); var configurationOptions = new PdfGenerateConfig(); configurationOptions.PageOrientation = PdfSharp.PageOrientation.Landscape; configurationOptions.PageSize = PdfSharp.PageSize.Letter; configurationOptions.MarginBottom = 19; configurationOptions.MarginLeft = 2; var output = PdfGenerator.GeneratePdf(HTMLstring.ToString(), configurationOptions); XFont font = new XFont("Segoe UI,Open Sans, sans-serif, serif", 7); XBrush brush = XBrushes.Black; var outputstream = new MemoryStream(); output.Save(outputstream); var temp = fc["spinnerToken"].ToString().Trim(); //WARNING : This is only for this example REMOVE IN REAL WORLD SCENARIO !!!!!!!!!!!!!!!!!!!!!!! //System.Threading.Thread.Sleep(5000); //WARNING : This is only for this example REMOVE IN REAL WORLD SCENARIO !!!!!!!!!!!!!!!!!!!!!!! downloadTimer.Stop(); string timeTookToDownload = downloadTimer.Elapsed.Days + " Days " + downloadTimer.Elapsed.Hours + " Hours " + downloadTimer.Elapsed.Minutes + " Minutes " + downloadTimer.Elapsed.Seconds + " Seconds " + downloadTimer.Elapsed.Milliseconds + " Milliseconds "; Session["spinnerToken"] = fc["spinnerToken"].ToString().Trim(); Session["timetooktodownload"] = timeTookToDownload; Response.BinaryWrite(outputstream.ToArray()); return(View("Index")); }
public void GenerarPDF() { PdfGenerateConfig config = new PdfGenerateConfig(); config.PageSize = PageSize.Letter; //config.SetMargins(30); config.MarginLeft = 15; config.MarginRight = 15; config.MarginBottom = 30; config.MarginTop = 30; string html = File.ReadAllText("C:\\Users\\k697344\\Documents\\Comex PPG\\Documentacion\\Ejemplo_3.html"); var doc = PdfGenerator.GeneratePdf(html, config); foreach (PdfPage page in doc.Pages) { double h = page.Height.Value; double w = page.Width.Value; XGraphics graph = XGraphics.FromPdfPage(page); string pathImgHeader = "C:\\Users\\k697344\\Documents\\Comex PPG\\Documentacion\\header.png"; XImage xImageHeader = XImage.FromFile(pathImgHeader); graph.DrawImage(xImageHeader, 0, 0, w - 10, 20); string pathImgFooter = "C:\\Users\\k697344\\Documents\\Comex PPG\\Documentacion\\footer.png"; XImage xImageFooter = XImage.FromFile(pathImgFooter); graph.DrawImage(xImageFooter, 10, h - 20, w - 10, 20); } var tmpFile = Path.GetTempFileName(); tmpFile = Path.GetFileNameWithoutExtension(tmpFile) + ".pdf"; //var tmpFile = Path.GetFileNameWithoutExtension(pathPDF) + ".pdf"; doc.Save(tmpFile); Process.Start(tmpFile); }
public Stream CreateFromHtmlString(string HtmlString) { var config = new PdfGenerateConfig { PageSize = PageSize.A4, PageOrientation = PageOrientation.Portrait }; config.SetMargins(16); var pdfDoc = PdfGenerator.GeneratePdf(HtmlString, config); var stream = new MemoryStream(); pdfDoc.Save(stream, false); pdfDoc.Dispose(); return(stream); }
private Byte[] PdfSharpConvert(String html) { var config = new PdfGenerateConfig() { MarginBottom = 20, MarginLeft = 40, MarginRight = 20, MarginTop = 20, PageSize = PageSize.A4, PageOrientation = PageOrientation.Portrait }; Byte[] res = null; using (MemoryStream ms = new MemoryStream()) { var pdf = PdfGenerator.GeneratePdf(html, config); pdf.Save(ms); res = ms.ToArray(); } return(res); }
/// <summary> /// Get Form Data /// </summary> /// <param name="formId"></param> /// <param name="manager"></param> /// <param name="dataModelManager"></param> /// <returns></returns> public static byte[] GetFormData(string formId, IManager manager, IDataModelManager dataModelManager) { byte[] data = { }; using (MemoryStream ms = new MemoryStream()) { var html = GetFormHtml(formId, manager, dataModelManager); MyFontResolverPdfSharp.Apply(); var config = new PdfGenerateConfig() { MarginBottom = 70, MarginLeft = 20, MarginRight = 20, MarginTop = 70, }; var pdf = PdfGenerator.GeneratePdf(html, PageSize.A4); pdf.Save(ms); data = ms.ToArray(); } return(data); }
public Stream Build(IEnumerable <IContent> contents) { string htmlContent = _htmlGenerator.GenerateHtml(contents, Descriptor.SupportedFileExtension); PdfGenerateConfig config = new PdfGenerateConfig(); config.PageSize = PdfSharp.PageSize.A4; config.SetMargins(20); //var doc = PdfGenerator.GeneratePdf(htmlContent, config, null, OnStylesheetLoad); var doc = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(htmlContent, config, null, OnStylesheetLoad); byte[] fileContents = null; using (MemoryStream stream = new MemoryStream()) { doc.Save(stream, true); fileContents = stream.ToArray(); } return(new MemoryStream(fileContents)); //using (var htmlStream = new MemoryStream(Encoding.UTF8.GetBytes(_htmlGenerator.GenerateHtml(contents, Descriptor.SupportedFileExtension)))) //using (var tmpStream = new MemoryStream()) //{ // htmlStream.CopyTo(tmpStream); // var apiKey = _siteService.GetSiteSettings().As<DownloadAsPdfSettingsPart>().CloudConvertApiKey; // var client = new RestClient("https://api.cloudconvert.org/"); // var request = new RestRequest("process"); // request.AddParameter("apikey", apiKey); // request.AddParameter("inputformat", "html"); // request.AddParameter("outputformat", "pdf"); // request.AddParameter("converter", "unoconv"); // var response = client.Post<InitResponse>(request); // var processUrl = response.Data.Url; // if (response.StatusCode != HttpStatusCode.OK) throw new OrchardException(T("PDF generation failed as the CloudConvert API returned an error when trying to open the converion process. Status code: {0}. CloudConvert error message: {1}.", response.StatusCode, response.Data.Error)); // var processClient = new RestClient("https:" + processUrl); // var uploadRequest = new RestRequest(); // uploadRequest.AddFile("file", tmpStream.ToArray(), "output.html"); // uploadRequest.AddParameter("input", "upload"); // uploadRequest.AddParameter("format", "pdf"); // var uploadResponse = processClient.Post(uploadRequest); // if (uploadResponse.StatusCode != HttpStatusCode.OK) throw new OrchardException(T("PDF generation failed as the CloudConvert API returned an error when trying to upload the HTML file. Status code: {0}.", uploadResponse.StatusCode)); // var processResponse = processClient.Get<ProcessResponse>(new RestRequest()); // var tryCount = 0; // while (processResponse.Data.Step != "finished" && tryCount < 20) // { // Thread.Sleep(2000); // Yes, doing this like this is bad. No better idea yet. // processResponse = processClient.Get<ProcessResponse>(new RestRequest()); // tryCount++; // } // if (tryCount == 20) throw new OrchardException(T("PDF generation failed as CloudConvert didn't finish the conversion after 40s.")); // using (var wc = new WebClient()) // { // var fileBytes = wc.DownloadData("https:" + processResponse.Data.Output.Url); // return new MemoryStream(fileBytes); // } //} }
private string ToFile() { string _stage = ""; string _filePath, _fullFilePath = ""; // Check file name null try { _stage = "Preparing temp path"; _filePath = Path.GetTempPath(); if (!FileName.ToUpper().EndsWith($".{FileType}")) { FileName += $".{FileType.ToString().ToLower()}"; } _fullFilePath = $"{_filePath}{FileName}"; if (File.Exists(_fullFilePath)) { // _stage = $"Deleting {_fullFilePath}"; File.Delete(_fullFilePath); } // _stage = $"Saving to {FileType} file"; switch (FileType) { case cMiscFunctions.eFileType.XLS: case cMiscFunctions.eFileType.TXT: using (FileStream _fs = File.Create(_fullFilePath)) { byte[] _info = new UTF8Encoding(true).GetBytes(Contents); // Add some information to the file. _fs.Write(_info, 0, _info.Length); } break; case cMiscFunctions.eFileType.PDF: var config = new PdfGenerateConfig(); if (Orientation.ToString().ToUpper() == "LANDSCAPE") { config.PageOrientation = PdfSharpCore.PageOrientation.Landscape; } else { config.PageOrientation = PdfSharpCore.PageOrientation.Portrait; } config.PageSize = PdfSharpCore.PageSize.A4; PdfDocument pdfDocument = PdfGenerator.GeneratePdf(Contents, config); pdfDocument.Save(_fullFilePath); break; default: throw new Exception("Non supported format"); } return(_fullFilePath); } catch (Exception ex) { throw new Exception($"[cProcess/ToFile#{_stage}] {ex.Message}."); } }
public static void GenerarPDF(DataTable dtPDF) { try { string pathPDF = "PDF/Reporte_Alumnos_" + DateTime.Now.ToString("dd_MM_yyyy_HH_mm_ss") + ".pdf"; StringBuilder htmlPDF = new StringBuilder(); PdfGenerateConfig config = new PdfGenerateConfig(); config.PageSize = PageSize.Undefined; config.ManualPageSize = new XSize(1191, 842); //config.PageOrientation = PageOrientation.Portrait; config.SetMargins(20); //AGREGAR TITULO htmlPDF.AppendLine("<div style='font-family: arial; position: relative;'>"); //EL TITULO DEL PDF htmlPDF.AppendLine("<center><h2>Reporte de Alumnos</h2></center>"); htmlPDF.AppendLine("<br />"); htmlPDF.AppendLine("<center>"); htmlPDF.AppendLine("<table border='0' cellspacing='0' cellpadding='0' style='width: 1150px; border-collapse: collapse; border-spacing: 0px; border: 0.5px solid black; font-family:arial; font-size:15px;'>"); //AGREGAR INFORMACION DE COLUMNAS htmlPDF.AppendLine("<thead style='background-color:#3B89D8; font-size:13px; color:white;'>"); htmlPDF.AppendLine("<tr>"); foreach (DataColumn dc in dtPDF.Columns) { htmlPDF.AppendLine("<th style='text-align:left; background-color:#3B89D8; border: 0.5px solid black;'>" + dc.ColumnName + "</th>"); } htmlPDF.AppendLine("</tr>"); htmlPDF.AppendLine("</thead>"); htmlPDF.AppendLine("<tbody>"); //AGREGAR INFORMACION DE REGISTROS int i = 0; string columnStyleHtml = string.Empty; foreach (DataRow dr in dtPDF.Rows.Cast <DataRow>().OrderBy(n => n["num_registro"])) { if ((i % 2) == 0) { columnStyleHtml = "background-color:#ffffff;"; htmlPDF.AppendLine("<tr style='" + columnStyleHtml + "'>"); } else { columnStyleHtml = "background-color:#CEE3F6;"; htmlPDF.AppendLine("<tr style='" + columnStyleHtml + "'>"); } foreach (object obj in dr.ItemArray) { htmlPDF.AppendLine("<td style='border: 0.5px solid black; text-align:center;'>" + obj.ToString() + "</td>"); } htmlPDF.AppendLine("</tr>"); } htmlPDF.AppendLine("</tbody>"); htmlPDF.AppendLine("</table>"); htmlPDF.AppendLine("</div>"); var doc = PdfGenerator.GeneratePdf(htmlPDF.ToString(), config); doc.Save(pathPDF); } catch (Exception ex) { throw ex; } }
/// <summary> /// Convierte el html a un arreglo de bytes, el cual es convertido por la dll de PdfSharp <3 /// </summary> /// <param name="html">es tu html en sí</param> /// <returns></returns> public byte[] makePDF(string html) { //Te dejo un ejemplo de un "Diploma" para ser impreso, ya tu podrás poner algo en su lugar var example_html = @" <center> <style> .signature, .title { float: left; border-top: 1px solid #000; width: 200px; text-align: center; } </style> <div style='width:100%; height:100%; padding:20px; text-align:center; border: 10px solid #787878'> <div style='width:100%; height:100%; padding:20px; text-align:center; border: 5px solid #787878'> <span style='font-size:50px; font-weight:bold'>Certificate of Completion</span><br /><br /> <span style='font-size:25px'><i>This is to certify that</i></span><br /><br /> <span style='font-size:30px'><b>$student.getFullName()</b></span><br /><br /><span style='font-size:25px'><i>hascompleted the course</i></span> <br /><br /> <span style='font-size:30px'>$course.getName()</span><br /><br /><span style='font-size:20px'>with score of <b>$grade.getPoints()%</b></span> <br /><br /><br /><br /> <span style='font-size:25px'><i>Completed Date</i></span><br /> <span style='font-size:25px'><i>01-Sep-2018</i></span><br /> <table style='margin-top:40px;float:left'> <tr> <td><span><b>$student.getFullName()</b></span></td> </tr> <tr> <td style='width:200px;float:left;border:0;border-bottom:1px solid #000;'></td> </tr> <tr> <td style='text-align:center'><span><b>Signature</b></span></td> </tr> </table> <table style='margin-top:40px;float:right'> <tr> <td><span><b>$student.getFullName()</b></span></td> </tr> <tr> <td style='width:200px;float:right;border:0;border-bottom:1px solid #000;'></td> </tr> <tr> <td style='text-align:center'><span><b>Signature</b></span></td> </tr> </table> </div> </div> </center> "; example_html = !String.IsNullOrEmpty(html) ? html : example_html; Byte[] res = null; using (MemoryStream ms = new MemoryStream()) { var config = new PdfGenerateConfig(); //Pongo la hoja en horizontal config.PageOrientation = PageOrientation.Landscape; //tamaño carta config.PageSize = PdfSharp.PageSize.A4; //que esa dll haga la magia var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(example_html, config); pdf.Save(ms); res = ms.ToArray(); } return(res); }