public void Genratepdftext(string text, string fname) { try { string temp_path = ""; PdfConverter pdfConverter_Transcrpit = new PdfConverter(); string temp1 = ""; pdfConverter_Transcrpit.LicenseKey = "eVJIWUtLWUtZTFdJWUpIV0hLV0BAQEA="; byte[] downloadBytes = pdfConverter_Transcrpit.GetPdfBytesFromHtmlString(text); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.AddHeader("Content-Type", "binary/octet-stream"); response.AddHeader("Content-Disposition", "attachment; filename=" + fname + ".pdf" + "; size=" + downloadBytes.Length.ToString()); response.Flush(); response.BinaryWrite(downloadBytes); response.Flush(); response.End(); } catch (Exception EX) { //return ""; throw EX; } }
public static bool GeneratePDF(string html, int id) { using (dbDataContext db = new dbDataContext()) { OSATBL_PWF_Zadost zadost = db.OSATBL_PWF_Zadosts.Where(a => a.id == id).FirstOrDefault(); if (zadost != null && zadost.pdf == null) { PdfConverter pdfConverter = new PdfConverter(); byte[] pdf = pdfConverter.GetPdfBytesFromHtmlString(html); zadost.pdf = new System.Data.Linq.Binary(pdf); //try //{ // FileStream fs = new FileStream(@"C:\Shared\" + id.ToString() + ".pdf", FileMode.OpenOrCreate, FileAccess.ReadWrite); // fs.Write(pdf, 0, pdf.Length); //} //catch (Exception) { } try { db.SubmitChanges(); return true; } catch (Exception) { } } return false; } }
public byte[] ToPdfBytes(ExportEventArgs exportEventArgs) { var converter = new PdfConverter { LicenseKey = Settings.Default.HtmlToPdfLicenseKey }; converter.PdfDocumentOptions.PdfPageSize = GetPdfPageSize(exportEventArgs); converter.PdfDocumentOptions.PdfPageOrientation = GetPageOrientation(exportEventArgs); converter.PdfDocumentOptions.LeftMargin = 18; converter.PdfDocumentOptions.RightMargin = 18; converter.PdfDocumentOptions.TopMargin = 18; converter.PdfDocumentOptions.BottomMargin = 18; converter.PdfDocumentOptions.GenerateSelectablePdf = true; converter.PdfDocumentOptions.FitWidth = true; converter.PageWidth = 1200; converter.AvoidTextBreak = true; converter.AvoidImageBreak = true; var html = exportEventArgs.ExportType == ExportType.CustomPdf ? exportEventArgs.Document : String.Format("<html><head>{0}</head><body><CENTER><BR/>{1}</center></body></html>", ExportPdfHelper.cssPdf, exportEventArgs.Document); return(converter.GetPdfBytesFromHtmlString(html)); }
/// <summary> /// 将HTML文件转换为PDF字节流 /// </summary> /// <param name="templateFile">模板文件名称</param> /// <param name="values">需要填充的值</param> /// <param name="impactOnCurrentYearData">表格形式的值</param> /// <param name="futureImpactData">表格形式的值</param> /// <returns>PDF字节流</returns> public static byte[] ConvertToPDFBytesWithComments(HtmlTempalteType templateType, Dictionary <string, string> values, List <SubmissionApprovalRecord> records) { var html = GenerateHtmlFromTemplateWithComments(templateType, values, records); var pdfConverter = new PdfConverter(); var bytes = pdfConverter.GetPdfBytesFromHtmlString(html); return(bytes); }
public static byte[] GenerateInvoicePdf(string htmlContent, string licenseKey) { var pdfConverter = new PdfConverter(); pdfConverter.LicenseKey = licenseKey; pdfConverter.InternetSecurityZone = InternetSecurityZone.LocalMachine; var pdfBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlContent); return(pdfBytes); }
private Document CrearDocumentoPDF(PdfConverter pdfConverter, string htmlOutput) { //realizo una primera conversion del html. byte[] byteArray = pdfConverter.GetPdfBytesFromHtmlString(htmlOutput); pdfConverter.PostConvertActionEvent += new PostConvertActionHandler(this.pdfConverter_PostConvertActionEvent2); Document result = pdfConverter.GetPdfDocumentObjectFromHtmlString(htmlOutput); pdfConverter.PostConvertActionEvent -= this.pdfConverter_PostConvertActionEvent2; return(result); }
public void Genratepdftext(string ptext, string fname) { try { string temp_path = ""; PdfConverter pdfobj = new PdfConverter(); string temp1 = ""; pdfobj.LicenseKey = "eVJIWUtLWUtZTFdJWUpIV0hLV0BAQEA="; pdfobj.PdfDocumentOptions.ShowHeader = true; pdfobj.PdfDocumentOptions.ShowFooter = true; string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri; thisPageURL = thisPageURL.Substring(0, thisPageURL.LastIndexOf('?')); string headerAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/header.htm"; pdfobj.PdfHeaderOptions.HtmlToPdfArea = new HtmlToPdfArea(headerAndFooterHtmlUrl); //enable header AddFooter(pdfobj); // set the header height in points pdfobj.PdfHeaderOptions.DrawHeaderLine = true; pdfobj.PdfHeaderOptions.HeaderHeight = 150; pdfobj.PdfHeaderOptions.HeaderText = ""; pdfobj.PdfHeaderOptions.HeaderSubtitleText = ""; pdfobj.PdfDocumentOptions.EmbedFonts = true; pdfobj.PdfDocumentInfo.AuthorName = "Cyber Best Technologies"; pdfobj.PdfDocumentInfo.Title = "Pharmacy Board"; pdfobj.PdfDocumentInfo.Subject = "Print LMS Forms"; //pdfobj.PdfDocumentInfo.Keywords = "HTML, PDF,Converter"; pdfobj.PdfDocumentInfo.CreatedDate = DateTime.Now; float width = (8.50f / 1.0f) * 72f; float height = (11 / 1.0f) * 72f; pdfobj.PdfDocumentOptions.AutoSizePdfPage = false; pdfobj.PdfDocumentOptions.PdfPageSize = PdfPageSize.Custom; pdfobj.PdfDocumentOptions.CustomPdfPageSize = new SizeF(width, height); pdfobj.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Portrait; pdfobj.PdfDocumentOptions.LeftMargin = 10; pdfobj.PdfDocumentOptions.RightMargin = 10; byte[] downloadBytes = pdfobj.GetPdfBytesFromHtmlString(ptext); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.AddHeader("Content-Type", "binary/octet-stream"); response.AddHeader("Content-Disposition", "attachment; filename=" + fname + ".pdf; size=" + downloadBytes.Length.ToString()); response.BinaryWrite(downloadBytes); } catch (Exception EX) { //return ""; throw EX; } }
public override void ExecuteResult(ControllerContext context) { context.HttpContext.Response.ContentType = ContentType; string baseURL = ""; string htmlString = this.Content; // Create the PDF converter. Optionally you can specify the virtual browser width as parameter. //1024 pixels is default, 0 means autodetect PdfConverter pdfConverter = new PdfConverter(); // set the converter options pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.Letter; pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal; pdfConverter.PdfDocumentOptions.ShowHeader = false; pdfConverter.PdfDocumentOptions.ShowFooter = false; pdfConverter.PdfDocumentOptions.BottomMargin = 60; pdfConverter.PdfDocumentOptions.TopMargin = 60; pdfConverter.PdfDocumentOptions.LeftMargin = 60; pdfConverter.PdfDocumentOptions.RightMargin = 60; pdfConverter.LicenseKey = "LwQeDxwcDx4XGA8dAR8PHB4BHh0BFhYWFg=="; // Performs the conversion and get the pdf document bytes that you can further // save to a file or send as a browser response // The baseURL parameterhelps the converter to get the CSS files and images // referenced by a relative URL in the HTML string. This option has efect only // if the HTML string contains a valid HEAD tag. // The converter will automatically inserts a <BASE HREF="baseURL"> tag. byte[] pdfBytes = null; if (baseURL.Length > 0) { pdfBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlString, baseURL); } else { pdfBytes = pdfConverter.GetPdfBytesFromUrl(htmlString); } // send the PDF document as a response to the browser for download // System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; context.HttpContext.Response.Clear(); // this.OutputFileName = Regex.Replace(this.OutputFileName, " ", "_", RegexOptions.IgnoreCase); // this.OutputFileName = StringHelper.StripNonAlphaNumeric(this.OutputFileName); context.HttpContext.Response.AddHeader("Content-Type", "application/pdf"); if (this.ReturnAsAttachment) { context.HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=" + this.OutputFileName + ".pdf; size=" + pdfBytes.Length.ToString()); } context.HttpContext.Response.Flush(); context.HttpContext.Response.BinaryWrite(pdfBytes); context.HttpContext.Response.Flush(); context.HttpContext.Response.End(); }
public void ExecuteResult() { try { bool selectablePDF = true; PdfConverter pdfConverter; // Create the PDF converter. Optionally you can specify the virtual browser width as parameter. //some pages require a custom height otherwise the data is cut off. pdfConverter = new PdfConverter(this.Width, this.Height); pdfConverter.PdfDocumentOptions.PdfPageSize = Winnovative.WnvHtmlConvert.PdfPageSize.Letter; if (System.Configuration.ConfigurationManager.AppSettings["htmltopdf.licensekey"] != String.Empty) { pdfConverter.LicenseKey = System.Configuration.ConfigurationManager.AppSettings["htmltopdf.licensekey"]; } pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.NoCompression; pdfConverter.PdfDocumentOptions.PdfPageOrientation = Winnovative.WnvHtmlConvert.PDFPageOrientation.Landscape; pdfConverter.PdfDocumentOptions.ShowHeader = false; pdfConverter.PdfDocumentOptions.ShowFooter = false; pdfConverter.PdfDocumentOptions.InternalLinksEnabled = false; pdfConverter.PdfDocumentOptions.JpegCompressionEnabled = false; pdfConverter.PdfDocumentOptions.StretchToFit = true; pdfConverter.OptimizeMemoryUsage = false; pdfConverter.PdfDocumentOptions.LiveUrlsEnabled = true; pdfConverter.PdfDocumentOptions.LeftMargin = 9; pdfConverter.PdfDocumentOptions.RightMargin = 9; pdfConverter.PdfDocumentOptions.TopMargin = 9; pdfConverter.PdfDocumentOptions.BottomMargin = 9; // set to generate selectable pdf or a pdf with embedded image pdfConverter.HtmlExcludedRegionsOptions.HtmlElementIds = new string[] { "Continuation" }; pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = selectablePDF; byte[] pdfBytes = null; pdfBytes = pdfConverter.GetPdfBytesFromHtmlString(this.HtmlString); CreatePdfFiles(pdfConverter, this.HtmlString); } catch (Exception ex) { string errormessage = ex.ToString(); string partsetupid = this.PartSetUpId.ToString(); } }
/// <summary> /// Generate the PDF invoice from the HTML template based on the current session data /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnGenerateInvoice_Click(object sender, EventArgs e) { if (!Page.IsValid) return; // save customer info on the session // to make it available in the report page SaveCustomerInfo(); // get the html string for the report StringWriter htmlStringWriter = new StringWriter(); Server.Execute("InvoiceTemplate.aspx", htmlStringWriter); string htmlCodeToConvert = htmlStringWriter.GetStringBuilder().ToString(); htmlStringWriter.Close(); //initialize the PdfConvert object PdfConverter pdfConverter = new PdfConverter(); // set the license key - required pdfConverter.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4; pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal; pdfConverter.PdfDocumentOptions.ShowHeader = false; pdfConverter.PdfDocumentOptions.ShowFooter = false; // get the base url for string conversion which is the url from where the html code was retrieved // the base url is used by the converter to get the full URL of the external CSS and images referenced by relative URLs string baseUrl = HttpContext.Current.Request.Url.AbsoluteUri; // get the pdf bytes from html string byte[] pdfBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlCodeToConvert, baseUrl); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.AddHeader("Content-Type", "application/pdf"); response.AddHeader("Content-Disposition", String.Format("attachment; filename=PdfInvoice.pdf; size={0}", pdfBytes.Length.ToString())); response.BinaryWrite(pdfBytes); // Note: it is important to end the response, otherwise the ASP.NET // web page will render its content to PDF document stream response.End(); }
protected void Page_Load(object sender, EventArgs e) { PdfConverter pdfConverter = new PdfConverter(); // pdfConverter.LicenseKey = "ORIIGQEZCAkJChkBFwkZCggXCAsXAAAAAA=="; string htmlContent = File.ReadAllText(@"D:\Full_report_html.txt"); var watch = System.Diagnostics.Stopwatch.StartNew(); // var html = RemoveWhitespaceFromHtmlPage(htmlContent); byte[] downloadBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlContent); watch.Stop(); var timeTakenToConvert = watch.ElapsedMilliseconds; System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.AddHeader("Content-Type", "application/pdf"); response.AddHeader("Content-Disposition", "attachment; filename=" + timeTakenToConvert + ".pdf; size=" + downloadBytes.Length.ToString()); response.Flush(); response.BinaryWrite(downloadBytes); response.Flush(); response.End(); }
public static byte[] GeneratePDF(string html, string title, int topMargin, int bottomMargin, int leftMargin, int rightMargin, Image backgroundImage) { var pdfConv = new PdfConverter { LicenseKey = "Z+n56Pv76Pn6/uj85vjo+/nm+frm8fHx8Q==" }; pdfConv.PdfDocumentOptions.TopMargin = topMargin; pdfConv.PdfDocumentOptions.BottomMargin = bottomMargin; pdfConv.PdfDocumentOptions.LeftMargin = leftMargin; pdfConv.PdfDocumentOptions.RightMargin = rightMargin; pdfConv.PdfDocumentOptions.EmbedFonts = true; // set header options pdfConv.PdfDocumentOptions.ShowHeader = true; pdfConv.PdfHeaderOptions.HeaderHeight = 50; AddHeaderElements(pdfConv); // set footer options pdfConv.PdfDocumentOptions.ShowFooter = true; pdfConv.PdfFooterOptions.FooterHeight = 50f; AddFooterElements(pdfConv); pdfConv.PdfDocumentInfo.Title = title; pdfConv.PdfDocumentInfo.CreatedDate = DateTime.Now; pdfConv.PdfDocumentInfo.AuthorName = ""; pdfConv.BeforeRenderPdfPageEvent += (BeforeRenderPdfPageParams args) => { var page = args.Page; var pageWidth = page.ClientRectangle.Width; var pageHeight = page.ClientRectangle.Height; var imageElement = new ImageElement(0, 0, pageWidth, pageHeight, backgroundImage); imageElement.Opacity = 60; page.AddElement(imageElement); }; return pdfConv.GetPdfBytesFromHtmlString(html, "http://www.thedrillbook.com/"); }
public byte[] ToPdfBytes(ExportEventArgs exportEventArgs) { var converter = new PdfConverter { LicenseKey = Settings.Default.HtmlToPdfLicenseKey }; converter.PdfDocumentOptions.PdfPageSize = GetPdfPageSize(exportEventArgs); converter.PdfDocumentOptions.PdfPageOrientation = GetPageOrientation(exportEventArgs); converter.PdfDocumentOptions.LeftMargin = 18; converter.PdfDocumentOptions.RightMargin = 18; converter.PdfDocumentOptions.TopMargin = 18; converter.PdfDocumentOptions.BottomMargin = 18; converter.PdfDocumentOptions.GenerateSelectablePdf = true; converter.PdfDocumentOptions.FitWidth = true; converter.PageWidth = 1200; converter.AvoidTextBreak = true; converter.AvoidImageBreak = true; var html = exportEventArgs.ExportType == ExportType.CustomPdf ? exportEventArgs.Document : String.Format("<html><head>{0}</head><body><CENTER><BR/>{1}</center></body></html>", ExportPdfHelper.cssPdf, exportEventArgs.Document); return converter.GetPdfBytesFromHtmlString(html); }
/// <summary> /// Generate PDF file with the whole html content /// </summary> /// <param name="contentHtml">internal content</param> /// <param name="fileName">export file name</param> public void GeneratePDF(string contentHtml, string fileName) { byte[] pdfBytes = pdfConverter.GetPdfBytesFromHtmlString(contentHtml); ExportPdfFile(pdfBytes, fileName); }
private void DownLoadPaperPDF() { string url = string.Format("http://{0}/ExamOnline/ExamPaperStorage/ExamPaperView.aspx?epid={1}&isPdf=1", Request.Url.Host, RequestEPID); BLL.Loger.Log4Net.Info("试卷导出PDF,访问URL:" + url); byte[] downloadBytes = new byte[] { }; string downloadName = "文字版试卷.pdf"; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "Get"; request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; request.KeepAlive = true; Uri uri = new Uri(url); CookieContainer cookies = new CookieContainer(); string name = BLL.Util.SysLoginCookieName; cookies.Add(uri, new Cookie(name, HttpContext.Current.Request.Cookies[name].Value)); request.CookieContainer = cookies; var s = request.GetResponse(); var r = new StreamReader(s.GetResponseStream(), Encoding.UTF8); var htmlText = r.ReadToEnd(); BLL.Loger.Log4Net.Info("试卷导出PDF—生成前文本内容:" + htmlText); htmlText = htmlText.Replace("<input name=", "<span name="); int iV = htmlText.IndexOf("<div class=\"taskT\">"); htmlText = htmlText.Replace("<div class=\"taskT\">", ""); if (iV > 0) { int iVLast = htmlText.IndexOf("div>", iV); if (iVLast > 0) { htmlText = htmlText.Substring(0, iV + 1) + htmlText.Substring(iVLast + 4); } } int iName = htmlText.IndexOf("iname=\"1\""); if (iName > 0) { int iNameE = htmlText.IndexOf("</b>", iName); if (iNameE > 0) { downloadName = HttpUtility.UrlEncode(htmlText.Substring(iName + 9 + 1, iNameE - iName - 10).Trim(), Encoding.UTF8).Replace("+", "%20") + ".pdf"; } } BLL.Loger.Log4Net.Info("试卷导出PDF—生成文件名:" + downloadName); PdfConverter pdfConverter = GetPdfConvert(); downloadBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlText); } catch (Exception ex) { downloadBytes = new byte[] { }; BLL.Loger.Log4Net.Error("在页面ExamPaperPDF.aspx 报错:" + ex.Message, ex); } try { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.AddHeader("Content-Type", "binary/octet-stream"); response.AddHeader("Content-Disposition", "attachment; filename=" + downloadName + "; size=" + downloadBytes.Length.ToString()); response.Flush(); response.BinaryWrite(downloadBytes); response.Flush(); response.End(); } catch (Exception ex) { BLL.Loger.Log4Net.Error("导出试卷pdf", ex); } }
/// <summary> /// 打印到文件 /// </summary> public void PrintToPDF(string sPrintContent) { try { string htmlString = sPrintContent; bool selectablePDF = true; PdfConverter pdfConverter = new PdfConverter(); // pdfConverterKey pdfConverter.LicenseKey = ConfigurationManager.AppSettings["pdfConverterKey"]; pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4; pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal; pdfConverter.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Portrait; pdfConverter.PdfDocumentOptions.ShowHeader = true; pdfConverter.PdfDocumentOptions.ShowFooter = true; pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = true; pdfConverter.PdfDocumentOptions.FitWidth = true; pdfConverter.PdfDocumentOptions.EmbedFonts = false; pdfConverter.PdfDocumentOptions.LiveUrlsEnabled = true; if (true) { pdfConverter.ScriptsEnabled = true; pdfConverter.ActiveXEnabled = true; } else { pdfConverter.ScriptsEnabledInImage = true; pdfConverter.ActiveXEnabledInImage = true; } pdfConverter.PdfDocumentOptions.JpegCompressionEnabled = true; if (false) { pdfConverter.PdfBookmarkOptions.TagNames = new string[] { "H1", "H2" }; } pdfConverter.PdfDocumentInfo.AuthorName = "ExperPDF HTML to PDF Converter"; if (true) AddHeader(pdfConverter); if (true) AddFooter(pdfConverter); byte[] pdfBytes = null; pdfBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlString); HttpResponse response = HttpContext.Current.Response; response.Clear(); response.AddHeader("Content-Type", "binary/octet-stream"); response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.pdf; size={1}", Guid.NewGuid(), pdfBytes.Length.ToString())); response.Flush(); response.BinaryWrite(pdfBytes); response.Flush(); response.End(); } catch (Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); } }
public void ConvertHTMLToPDF(string html, string downloadName) { byte[] downloadBytes = pdfConverter.GetPdfBytesFromHtmlString(html); DownloadPDF(downloadBytes, downloadName); }
public byte[] GeneratePdfBytesUsingComponent(string sHtml, string headerLeft, string footer, bool putHeaderDate = true) { PdfConverter pdfConverter = new PdfConverter(); pdfConverter = GeneratePdfConverter(headerLeft, footer, putHeaderDate); Byte[] downloadBytes = pdfConverter.GetPdfBytesFromHtmlString(sHtml); return downloadBytes; }
public byte[] ConvertHTMLStringToPDF(string htmlString, string baseURL, bool selectablePDF, bool AddHeader, bool AddFooter, bool FitWidth, bool EmbedFonts, bool LiveLinks, bool ClientScripts, bool JpegCompression, bool Bookmarks, int PageSize, int CompressionLevel, bool Orientation) { baseURL = baseURL.Trim(); EmbedFontsPDF= EmbedFonts; // Crear el convertidor de formato PDF. Opcionalmente, el ancho de visor HTML se puede especificar como parámetro // El ancho por defecto HTML visor es de 1024 píxeles. PdfConverter pdfConverter = new PdfConverter(); // Establecer la clave de licencia pdfConverter.LicenseKey = "QGtxYHNzYHF2dXNgc25wYHNxbnFybnl5eXk="; /* Establece las opciones del convertidor */ // Tamaño de hoja // 1: Carta - 2: Oficio - 3: A4 - Defaul: Carta switch (PageSize) { case 1: pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.Letter; break; case 2: pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.Legal; break; case 3: pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4; break; default: pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.Letter; break; } // Nivel de Compresion // 1: Normal - 2: No Comprimido - 3: El Mejor - Default: Normal switch (CompressionLevel) { case 1: pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal; break; case 2: pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.NoCompression; break; case 3: pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Best; break; default: pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal; break; } // Orientacion pagina // 1: Vertical - 2: Horizontal - Default: Vertical if (Orientation) { pdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait; } else { pdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Landscape; } // Establecer si cabecera y el pie se muestran en el archivo PDF - opcional - por defecto es false pdfConverter.PdfDocumentOptions.ShowHeader = AddHeader; pdfConverter.PdfDocumentOptions.ShowFooter = AddFooter; // Establecer si el contenido HTML se cambia, el tamaño si es necesario para ajustarse al ancho de página del PDF // Por defecto es cierto pdfConverter.PdfDocumentOptions.FitWidth = FitWidth; // Establecer la opción de fuentes incrustadas - opcional - por defecto es false pdfConverter.PdfDocumentOptions.EmbedFonts = EmbedFonts; // Establecer la opción de enlaces en vivo HTTP - opcional - por defecto es cierto pdfConverter.PdfDocumentOptions.LiveUrlsEnabled = LiveLinks; // Establece si el JavaScript está activado durante la conversión a formato PDF - por defecto es cierto pdfConverter.JavaScriptEnabled = ClientScripts; // Establecer si las imágenes en formato PDF están comprimidas con JPEG para reducir el tamaño del documento PDF // Por defecto es cierto pdfConverter.PdfDocumentOptions.JpegCompressionEnabled = JpegCompression; // enable auto-generated bookmarks for a specified list of tags (e.g. H1 and H2) if (Bookmarks) { pdfConverter.PdfBookmarkOptions.HtmlElementSelectors = new string[] { "H1", "H2" }; } // Agregar HTML header if (AddHeader) AddHeaderPDF(pdfConverter); // Agregar HTML footer if (AddFooter) AddFooterPDF(pdfConverter); // Realiza la conversión y obtener los bytes de documentos PDF que se pueden seguir // Guardar en un archivo o enviar como respuesta al navegador // // El parámetro baseURL ayuda a que el convertidor para obtener los archivos CSS y las imágenes // Hace referencia a una dirección URL relativa en la cadena de HTML. byte[] pdfBytes = null; if (baseURL.Length > 0) pdfBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlString, baseURL); else pdfBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlString); // Enviar el documento PDF como una respuesta al navegador para su descarga //System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; //response.Clear(); //response.AddHeader("Content-Type", "application/pdf"); //response.BinaryWrite(pdfBytes); //// Nota: es importante para poner fin a la respuesta, de lo contrario el ASP.NET //// Página web hará que su contenido para transmitir en formato PDF //response.End(); return pdfBytes; }
/// <summary> /// Create a pdf write it into a stream /// </summary> /// <param name="content">The html content</param> /// <param name="s">The stream</param> public void CreateInStream(Stream s) { byte[] pdfbyte = _Converter.GetPdfBytesFromHtmlString(Content, HttpContext.Current.Request.ApplicationPath); s.Write(pdfbyte, 0, pdfbyte.Length); s.Flush(); }
public override void ExecuteResult(ControllerContext context) { try { context.HttpContext.Response.ContentType = ContentType; string baseURL = ""; string htmlString = this.Content; bool selectablePDF = true; PdfConverter pdfConverter; // Create the PDF converter. Optionally you can specify the virtual browser width as parameter. //some pages require a custom height otherwise the data is cut off. pdfConverter = new PdfConverter(this.Width, this.Height); //If there is no license key, defaults to demo version if (ConfigurationManager.AppSettings["htmltopdf.licensekey"] != String.Empty) { pdfConverter.LicenseKey = ConfigurationManager.AppSettings["htmltopdf.licensekey"]; } pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.NoCompression; pdfConverter.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Portrait; pdfConverter.PdfDocumentOptions.ShowHeader = false; pdfConverter.PdfDocumentOptions.ShowFooter = false; pdfConverter.PdfDocumentOptions.StretchToFit = true; pdfConverter.PdfDocumentOptions.InternalLinksEnabled = true; pdfConverter.OptimizePdfPageBreaks = true; pdfConverter.PdfDocumentOptions.LiveUrlsEnabled = true; // pdfConverter.PdfDocumentOptions.FitWidth = true; // pdfConverter.PdfDocumentOptions.FitHeight = true; pdfConverter.PdfDocumentOptions.LeftMargin = 3; pdfConverter.PdfDocumentOptions.RightMargin = 3; pdfConverter.PdfDocumentOptions.TopMargin = 3; pdfConverter.PdfDocumentOptions.BottomMargin = 3; // set to generate selectable pdf or a pdf with embedded image pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = selectablePDF; byte[] pdfBytes = null; if (baseURL.Length > 0) { pdfBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlString, baseURL); } else { pdfBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlString); } // send the PDF document as a response to the browser for download // System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; context.HttpContext.Response.Clear(); context.HttpContext.Response.AddHeader("Content-Type", "application/pdf"); if (this.ReturnAsAttachment) { //add timestamp to outputted file string timestamp = DateTime.Now.ToString("yyyy_MM_dd_HHmmssffff"); context.HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=" + this.OutputFileName + timestamp + ".pdf; size=" + pdfBytes.Length.ToString()); } //Disabling buffering so that, the file content is immediately written to output stream context.HttpContext.Response.Buffer = false; context.HttpContext.Response.BinaryWrite(pdfBytes); //No need to Flush() and End() the response as the ouptpu stream is not buffered. //These were commented out because it was causing an error whenever the user cancelled the download // context.HttpContext.Response.Flush(); // context.HttpContext.Response.End(); // context.HttpContext.Response.RedirectToRoute("index"); } catch (Exception ex) { //if the error occurs because the user clicks the "x" on the open/save pdf dialog box just swallow, otherwise log via elmah if ((ex.GetBaseException() is System.Web.HttpException) == false) { throw ex; } } }
//RCA 10/08/2017 //se cambio el metodo para que recibiera byte y asi no tenga que guardar el archivo en la carpeta de temporales. //solo recibe el parametro del cuerpo public byte[] GenerarPDF(string Cuerpo) //public String GenerarPDF(string Cuerpo, string RutaBase) { PdfConverter pdfConverter = new PdfConverter(); //RCA 10/08/2017 byte[] bPdf = null; string error = string.Empty; try { //CARACTERISTICAS Y FORMATO DE ARCHIVO PDF pdfConverter.LicenseKey = "f1ROX0dfTk9OTl9KUU9fTE5RTk1RRkZGRg=="; //RCA 10/08/2017 //para que lo que se muestre el texto del pdf pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = true; pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.Letter; pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal; //pdfConverter.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Portrait; //pdfConverter.PdfDocumentOptions.ShowHeader = true; //pdfConverter.PdfDocumentOptions.ShowFooter = true; pdfConverter.PdfDocumentOptions.BottomMargin = 25; pdfConverter.PdfDocumentOptions.TopMargin = 5; pdfConverter.PdfDocumentOptions.RightMargin = 50; pdfConverter.PdfDocumentOptions.LeftMargin = 50; pdfConverter.PdfDocumentOptions.StretchToFit = true; //FORMATO Y TEXTO PARA ENCABEZADO DE PÁGINA //pdfConverter.PdfSecurityOptions.CanCopyContent = true; //pdfConverter.PdfHeaderOptions.HeaderTextFontSize = 6; //pdfConverter.PdfFooterOptions.FooterTextFontSize = 6; //pdfConverter.PdfHeaderOptions.HeaderHeight = 120; //pdfConverter.PdfHeaderOptions.HeaderTextYLocation = 81; //pdfConverter.PdfFooterOptions.ShowPageNumber = true; //pdfConverter.PdfHeaderOptions.ShowOnEvenPages = true; //pdfConverter.PdfHeaderOptions.DrawHeaderLine = false; //pdfConverter.PdfFooterOptions.DrawFooterLine = false; //pdfConverter.PdfFooterOptions.PageNumberingStartIndex = 0; //pdfConverter.PdfFooterOptions.PageNumberingFormatString = "Dictamen Pág. &p; de &P;"; //pdfConverter.PdfSecurityOptions.CanPrint = true; //Se borran los archivos del dia anterior /*Directory.GetFiles(RutaBase + @"ArchivosTemporales\") * .Select(f => new FileInfo(f)) * .Where(f => f.LastAccessTime < DateTime.Now.AddDays(-1)) * .ToList() * .ForEach(f => f.Delete());*/ //string rutaArchivo = RutaBase + @"ArchivosTemporales\" + Path.GetFileName(System.IO.Path.GetRandomFileName()); //RCA 10/08/2017 //usar el metodo gettempfile sirve para Crea un archivo temporal de cero bytes y nombre único en el disco y devuelve la ruta de acceso completa a ese archivo. //string rutaArchivo = RutaBase + @"ArchivosTemporales\" + Path.GetFileName(System.IO.Path.GetTempFileName()); //RCA 10/08/2017 bPdf = pdfConverter.GetPdfBytesFromHtmlString(Cuerpo); //pdfConverter.SavePdfFromHtmlStringToFile(Cuerpo, rutaArchivo); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "application/pdf"; HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=Acuse.pdf"); //HttpContext.Current.Response.TransmitFile(rutaArchivo); //RCA 10/08/2017 HttpContext.Current.Response.BinaryWrite(bPdf); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); } catch (Exception ex) { error = "No se puedo generar el archivo PDF debido a: " + ex.ToString(); } //RCA 10/08/2017 pdfConverter = null; return(bPdf); //return error; }
protected override void Render(HtmlTextWriter writer) { base.Render(writer); if (_swPdf != null) { string htmlToConvert = _swPdf.GetStringBuilder().ToString(); PdfConverter pdfConverter = new PdfConverter(); pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.Letter; pdfConverter.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Landscape; pdfConverter.PdfDocumentOptions.LeftMargin = 36; //36/72 = 0.5 in pdfConverter.PdfDocumentOptions.RightMargin = 36; //36/72 = 0.5 in string[] strReport = this.Page.Request.FilePath.Split('/'); string reportId = strReport.LastOrDefault().Replace("R", "").Replace('_', '.').Replace(".aspx", ""); if (string.IsNullOrEmpty(reportId)) { reportId = "SampleReport"; } //TODO: Show 130.16: SKUs in a PO. How to manage font. Investigate top and bottom margins string strHeader;// = string.Format("{0}:{1}", SiteMap.CurrentNode["ReportId"], SiteMap.CurrentNode.Title); if (SiteMap.CurrentNode != null) { strHeader = string.Format("{0}:{1}", SiteMap.CurrentNode["ReportId"], SiteMap.CurrentNode.Title); } else { strHeader = string.Format("{0}:{1}", reportId, this.Page.Title); } pdfConverter.PdfHeaderOptions.HeaderText = strHeader; //pdfConverter.PdfHeaderOptions.HeaderSubtitleText = string.Format("Report generated on {0:D}", DateTime.Now); pdfConverter.PdfDocumentOptions.ShowHeader = true; pdfConverter.PdfDocumentOptions.ShowFooter = true; pdfConverter.PdfFooterOptions.FooterText = string.Format("Report generated on {0:D}", DateTime.Now); pdfConverter.PdfFooterOptions.ShowPageNumber = true; //TODO: Set more properties and in generic fashion pdfConverter.PdfDocumentInfo.CreatedDate = DateTime.Now; pdfConverter.PdfDocumentInfo.AuthorName = HttpContext.Current.User.Identity.Name; pdfConverter.ScriptsEnabled = true; pdfConverter.PdfDocumentOptions.LiveUrlsEnabled = false; if (SiteMap.CurrentNode != null) { pdfConverter.PdfDocumentInfo.Title = SiteMap.CurrentNode.Title; pdfConverter.PdfDocumentInfo.Keywords = SiteMap.CurrentNode.Description; //SiteMap.CurrentNode["Description"]; pdfConverter.PdfDocumentInfo.Subject = string.Format("{0}: {1}", SiteMap.CurrentNode["ReportId"], SiteMap.CurrentNode.Title); } else { pdfConverter.PdfDocumentInfo.Title = this.Page.Title; pdfConverter.PdfDocumentInfo.Keywords = "Sample Report"; pdfConverter.PdfDocumentInfo.Subject = string.Format("{0}: {1}", reportId, this.Page.Title); } //pdfConverter.ColorSpace = ColorSpace.Gray; byte[] pdfBytes = null; pdfBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlToConvert, this.Request.Url.AbsoluteUri); if (SiteMap.CurrentNode != null) { strHeader = string.Format("attachment; filename={0}.pdf; size=", SiteMap.CurrentNode["reportId"]); } else { strHeader = string.Format("attachment; filename={0}.pdf; size=", reportId); } Response.AddHeader("Content-Disposition", strHeader + pdfBytes.Length.ToString()); Response.BinaryWrite(pdfBytes); } }
/// <summary> /// Convert the specified HTML string to a PDF document and send the /// document to the browser /// </summary> private void ConvertHTMLStringToPDF() { string htmlString = textBoxHTMLCode.Text; string baseURL = textBoxBaseURL.Text.Trim(); bool selectablePDF = radioConvertToSelectablePDF.Checked; // Create the PDF converter. Optionally the HTML viewer width can be specified as parameter // The default HTML viewer width is 1024 pixels. PdfConverter pdfConverter = new PdfConverter(); // set the license key pdfConverter.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; // set the converter options pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4; pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal; pdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait; // set if header and footer are shown in the PDF - optional - default is false pdfConverter.PdfDocumentOptions.ShowHeader = cbAddHeader.Checked; pdfConverter.PdfDocumentOptions.ShowFooter = cbAddFooter.Checked; // set if the HTML content is resized if necessary to fit the PDF page width - default is true pdfConverter.PdfDocumentOptions.FitWidth = cbFitWidth.Checked; // // set the embedded fonts option - optional - default is false pdfConverter.PdfDocumentOptions.EmbedFonts = cbEmbedFonts.Checked; // set the live HTTP links option - optional - default is true pdfConverter.PdfDocumentOptions.LiveUrlsEnabled = cbLiveLinks.Checked; // set if the JavaScript is enabled during conversion to a PDF - default is true pdfConverter.JavaScriptEnabled = cbClientScripts.Checked; // set if the images in PDF are compressed with JPEG to reduce the PDF document size - default is true pdfConverter.PdfDocumentOptions.JpegCompressionEnabled = cbJpegCompression.Checked; // enable auto-generated bookmarks for a specified list of tags (e.g. H1 and H2) if (cbBookmarks.Checked) { pdfConverter.PdfBookmarkOptions.HtmlElementSelectors = new string[] { "H1", "H2" }; } // add HTML header if (cbAddHeader.Checked) AddHeader(pdfConverter); // add HTML footer if (cbAddFooter.Checked) AddFooter(pdfConverter); // Performs the conversion and get the pdf document bytes that can be further // saved to a file or sent as response to browser // // The baseURL parameter helps the converter to get the CSS files and images // referenced by a relative URL in the HTML string. byte[] pdfBytes = null; if (baseURL.Length > 0) pdfBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlString, baseURL); else pdfBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlString); // send the generated PDF document to client browser // get the object representing the HTTP response to browser HttpResponse httpResponse = HttpContext.Current.Response; // add the Content-Type and Content-Disposition HTTP headers httpResponse.AddHeader("Content-Type", "application/pdf"); if (radioAttachment.Checked) httpResponse.AddHeader("Content-Disposition", String.Format("attachment; filename=GettingStarted.pdf; size={0}", pdfBytes.Length.ToString())); else httpResponse.AddHeader("Content-Disposition", String.Format("inline; filename=GettingStarted.pdf; size={0}", pdfBytes.Length.ToString())); // write the PDF document bytes as attachment to HTTP response httpResponse.BinaryWrite(pdfBytes); // Note: it is important to end the response, otherwise the ASP.NET // web page will render its content to PDF document stream httpResponse.End(); }
//metodo para crear el pdf al vuelo del saef public byte[] FormarPDF(string HTML, string fileName, string Cabecera, string Pie, string Folio, bool nuevo) { PdfConverter pdfConverter = new PdfConverter(); byte[] bPdf = null; byte[] bResp = null; try { pdfConverter.LicenseKey = "f1ROX0dfTk9OTl9KUU9fTE5RTk1RRkZGRg=="; //Header pdfConverter.PdfDocumentOptions.ShowHeader = true; pdfConverter.PdfHeaderOptions.HeaderHeight = 190; pdfConverter.PdfHeaderOptions.HtmlToPdfArea = new HtmlToPdfArea(Cabecera, null); pdfConverter.PdfHeaderOptions.DrawHeaderLine = false; if (nuevo == false) { //pie pdfConverter.PdfFooterOptions.FooterHeight = 100; pdfConverter.PdfFooterOptions.HtmlToPdfArea = new HtmlToPdfArea(Pie, null); pdfConverter.PdfDocumentOptions.ShowFooter = true; pdfConverter.PdfFooterOptions.DrawFooterLine = false; } //poner el numero de paginacion pdfConverter.PdfFooterOptions.TextArea = new TextArea(5, -5, "Página &p; de &P; ", new System.Drawing.Font(new System.Drawing.FontFamily("Arial"), 8, System.Drawing.GraphicsUnit.Point)); pdfConverter.PdfFooterOptions.TextArea.EmbedTextFont = true; pdfConverter.PdfFooterOptions.TextArea.TextAlign = HorizontalTextAlign.Right; pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.Letter; pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal; //margenes pdfConverter.PdfDocumentOptions.LeftMargin = 40; pdfConverter.PdfDocumentOptions.RightMargin = 40; pdfConverter.PdfDocumentOptions.StretchToFit = true; bPdf = pdfConverter.GetPdfBytesFromHtmlString(HTML); if (nuevo) { //metodo para poner el logo de fondo try { string rutaFondo = "https://sistemas.indaabin.gob.mx/ImagenesComunes/nuevoescudo.png"; MemoryStream stream = new MemoryStream(); iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(bPdf); //crear el objeto pdfstamper que se utiliza para agregar contenido adicional al archivo pdf fuente iTextSharp.text.pdf.PdfStamper pdfStamper = new iTextSharp.text.pdf.PdfStamper(pdfReader, stream); //iterar a través de todas las páginas del archivo fuente pdf for (int pageIndex = 1; pageIndex <= pdfReader.NumberOfPages; pageIndex++) { PdfContentByte overContent = pdfStamper.GetOverContent(pageIndex); iTextSharp.text.Image jpeg = iTextSharp.text.Image.GetInstance(rutaFondo); overContent.SaveState(); overContent.SetGState(new PdfGState { FillOpacity = 0.3f, StrokeOpacity = 0.3f//0.3 }); overContent.AddImage(jpeg, 560f, 0f, 0f, 820f, 0f, 0f); overContent.RestoreState(); } //cerrar stamper y filestream de salida pdfStamper.Close(); stream.Close(); pdfReader.Close(); bResp = stream.ToArray(); pdfStamper = null; pdfReader = null; stream = null; } catch (Exception ex) { } } HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "application/pdf"; HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=Acessibilidad" + " " + fileName + " " + Folio + ".pdf"); if (nuevo) { HttpContext.Current.Response.BinaryWrite(bResp); } else { HttpContext.Current.Response.BinaryWrite(bPdf); } HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); } catch (Exception ex) { } return(bPdf); //return bPdf; }
public byte[] GeneraPdfFromHtmlStr(string cadHtml) { PdfConverter pdfConverter = new PdfConverter(); byte[] bPdf = null; string header = ""; string footer = ""; string tagIniEncab = "@@ENCAB@@"; string tagFinEncab = "@@FINENCAB@@"; string tagIniPie = "@@PIE@@"; string tagFinPie = "@@FINPIE@@"; int iniEncab = 0; int finEncab = 0; int iniPie = 0; int finPie = 0; iniEncab = cadHtml.IndexOf(tagIniEncab); finEncab = cadHtml.IndexOf(tagFinEncab); iniPie = cadHtml.IndexOf(tagIniPie); finPie = cadHtml.IndexOf(tagFinPie); try { if (iniEncab > 0 && finEncab > 0) { header = cadHtml.Substring((iniEncab + tagIniEncab.Length), (finEncab - iniEncab - tagIniEncab.Length)).Trim(); } if (iniPie > 0 && finPie > 0) { footer = cadHtml.Substring((iniPie + tagIniPie.Length), (finPie - iniPie - tagIniPie.Length)).Trim(); } pdfConverter.LicenseKey = "f1ROX0dfTk9OTl9KUU9fTE5RTk1RRkZGRg=="; pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = true; pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.Letter; pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal; pdfConverter.ActiveXEnabledInImage = true; //los margenes se manejan en puntos 72 por pulgada pdfConverter.PdfDocumentOptions.LeftMargin = 43;//aproximandamente 1.5cm pdfConverter.PdfDocumentOptions.RightMargin = 43; if (header.Length > 0) { pdfConverter.PdfDocumentOptions.ShowHeader = true; pdfConverter.PdfHeaderOptions.HeaderHeight = 80; pdfConverter.PdfHeaderOptions.HtmlToPdfArea = new HtmlToPdfArea(header, null); pdfConverter.PdfHeaderOptions.DrawHeaderLine = false; } else { pdfConverter.PdfDocumentOptions.TopMargin = 43; } //numero de pagina pdfConverter.PdfDocumentOptions.ShowFooter = true; pdfConverter.PdfFooterOptions.FooterHeight = 43; //pdfConverter.PdfFooterOptions.TextArea = new TextArea(0, 5, "Página &p; de &P; ", //new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 10, //System.Drawing.GraphicsUnit.Point)); //pdfConverter.PdfFooterOptions.TextArea.EmbedTextFont = true; //pdfConverter.PdfFooterOptions.TextArea.TextAlign = HorizontalTextAlign.Right; pdfConverter.PdfFooterOptions.DrawFooterLine = false; if (footer.Length > 0) { pdfConverter.PdfFooterOptions.FooterHeight = 72; pdfConverter.PdfFooterOptions.HtmlToPdfArea = new HtmlToPdfArea(footer, null); } bPdf = pdfConverter.GetPdfBytesFromHtmlString(cadHtml); } catch (Exception ex) { } pdfConverter = null; return(bPdf); }
/// <summary> /// Gets a PDF document from the URL passed in, and returns to user in the HttpResponse (as a download) /// </summary> /// <param name="inUrl"></param> /// <param name="inPasswordProtectRandomly"></param> /// <param name="inOrientation"></param> /// <param name="inPageSize"></param> /// <param name="inServer">The requesting server (Page.Server when requested by an aspx or ascx page)</param> /// <param name="pdfFooterOptions"></param> /// <param name="pdfHeaderOptions"></param> /// <returns></returns> public static byte[] GetPDFfromURL(string inUrl, bool inPasswordProtectRandomly, PDFPageOrientation inOrientation, PdfPageSize inPageSize, HttpServerUtility inServer, PdfHeaderOptions pdfHeaderOptions, PdfFooterOptions pdfFooterOptions) { // get the html string for the report string htmlCodeToConvert = getPageAsHtml(inUrl, inServer); //initialize the PdfConvert object PdfConverter pdfConverter = new PdfConverter(); pdfConverter.NavigationTimeout = 120; pdfConverter.PdfDocumentOptions.PdfPageSize = inPageSize; pdfConverter.PdfDocumentOptions.PdfPageOrientation = inOrientation; pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal; pdfConverter.PdfDocumentOptions.LeftMargin = 15; pdfConverter.PdfDocumentOptions.TopMargin = 15; pdfConverter.PdfDocumentOptions.RightMargin = 0; pdfConverter.PdfDocumentOptions.BottomMargin = 15; //set header and footer options. if (pdfHeaderOptions != null) { if (!string.IsNullOrEmpty(pdfHeaderOptions.HeaderText)) { pdfConverter.PdfDocumentOptions.ShowHeader = true; pdfConverter.PdfHeaderOptions.DrawHeaderLine = pdfHeaderOptions.DrawHeaderLine; pdfConverter.PdfHeaderOptions.HeaderText = pdfHeaderOptions.HeaderText; pdfConverter.PdfHeaderOptions.HeaderHeight = pdfHeaderOptions.HeaderHeight; pdfConverter.PdfHeaderOptions.HeaderTextFontSize = pdfHeaderOptions.HeaderTextFontSize; pdfConverter.PdfHeaderOptions.HeaderTextAlign = pdfHeaderOptions.HeaderTextAlign; pdfConverter.PdfHeaderOptions.HeaderTextColor = pdfHeaderOptions.HeaderTextColor; } pdfConverter.PdfHeaderOptions.ShowOnEvenPages = pdfHeaderOptions.ShowOnEvenPages; pdfConverter.PdfHeaderOptions.ShowOnOddPages = pdfHeaderOptions.ShowOnOddPages; pdfConverter.PdfHeaderOptions.ShowOnFirstPage = pdfHeaderOptions.ShowOnFirstPage; } if (pdfFooterOptions != null) { pdfConverter.PdfDocumentOptions.ShowFooter = true; if (!string.IsNullOrEmpty(pdfFooterOptions.FooterText)) { pdfConverter.PdfFooterOptions.FooterText = pdfFooterOptions.FooterText; pdfConverter.PdfFooterOptions.FooterTextColor = pdfFooterOptions.FooterTextColor; pdfConverter.PdfFooterOptions.FooterTextFontSize = pdfFooterOptions.FooterTextFontSize; } pdfConverter.PdfFooterOptions.DrawFooterLine = pdfFooterOptions.DrawFooterLine; if (pdfFooterOptions.FooterHeight > 0) { pdfConverter.PdfFooterOptions.FooterHeight = pdfFooterOptions.FooterHeight; } pdfConverter.PdfFooterOptions.ShowPageNumber = pdfFooterOptions.ShowPageNumber; pdfConverter.PdfFooterOptions.ShowOnEvenPages = pdfFooterOptions.ShowOnEvenPages; pdfConverter.PdfFooterOptions.ShowOnOddPages = pdfFooterOptions.ShowOnOddPages; pdfConverter.PdfFooterOptions.ShowOnFirstPage = pdfFooterOptions.ShowOnFirstPage; } pdfConverter.AvoidTextBreak = true; pdfConverter.AvoidImageBreak = true; pdfConverter.LicenseKey = "HDcuPC4uPC4oLiU8KTIsPC8tMi0uMiUlJSU="; if (inPasswordProtectRandomly) { pdfConverter.AuthenticationOptions.Username = "******"; pdfConverter.AuthenticationOptions.Password = new Guid().ToString(); } // set the demo license key //pdfConverter.LicenseKey = "put your license key here"; // get the base url for string conversion which is the url from where the html code was retrieved // the base url is a hint for the converter to find the external CSS and images referenced by relative URLs string baseUrl = HttpContext.Current.Request.Url.AbsoluteUri; // get the pdf bytes from html string byte[] downloadBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlCodeToConvert, baseUrl); return(downloadBytes); }
public static byte[] GeneratePDFWithHeaderFooter(string HtmlString, string headerHtmlId, string footerHtmlId) { string pdfConverterLicenseKey = "fvDg8eDx4+jx6P/h8eLg/+Dj/+jo6Og="; byte[] pdfBytes = null; PdfConverter pdfConverter = new PdfConverter(); pdfConverter.LicenseKey = pdfConverterLicenseKey; pdfConverter.PdfDocumentOptions.EmbedFonts = false; pdfConverter.PdfDocumentOptions.TopMargin = 10; pdfConverter.PdfDocumentOptions.RightMargin = 10; pdfConverter.PdfDocumentOptions.LeftMargin = 10; pdfConverter.PdfDocumentOptions.BottomMargin = 30; var headerBlock = ""; var footerBlock = ""; HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); TextReader htmlReader = new StringReader(HtmlString.Replace(" ", " ")); doc.Load(htmlReader); // Install a handler where to change the header and footer in first page //pdfConverter.PrepareRenderPdfPageEvent += new PrepareRenderPdfPageDelegate(htmlToPdfConverter_PrepareRenderPdfPageEvent); //Header control pdfConverter.PdfDocumentOptions.ShowHeader = true; headerBlock = doc.GetElementbyId(headerHtmlId).InnerHtml; HtmlToPdfElement headerHtml = new HtmlToPdfElement(0, 0, 600, headerBlock, ""); //headerHtml.FitHeight = true; //用了會變小 pdfConverter.PdfHeaderOptions.HeaderHeight = 180; headerHtml.FitWidth = true; headerHtml.EmbedFonts = true; pdfConverter.PdfHeaderOptions.AddElement(headerHtml); pdfConverter.PdfHeaderOptions.PageNumberingStartIndex = 1; //footer control pdfConverter.PdfDocumentOptions.ShowFooter = true; footerBlock = doc.GetElementbyId(footerHtmlId).InnerHtml; HtmlToPdfElement footerHtml = new HtmlToPdfElement(0, 0, 570, footerBlock, ""); pdfConverter.PdfFooterOptions.FooterHeight = 250; footerHtml.FitWidth = true; footerHtml.EmbedFonts = true; pdfConverter.PdfFooterOptions.AddElement(footerHtml); pdfConverter.PdfFooterOptions.PageNumberingStartIndex = 2; pdfConverter.PdfFooterOptions.PageNumberingPageCountIncrement = 1; HtmlString = HtmlString.Replace("id=\"" + headerHtmlId + "\"", "id=\"" + headerHtmlId + "\"" + " style ='display:none;'"); HtmlString = HtmlString.Replace("id=\"" + footerHtmlId + "\"", "id=\"" + footerHtmlId + "\"" + " style ='display:none;'"); pdfBytes = pdfConverter.GetPdfBytesFromHtmlString(HtmlString); return(pdfBytes); }