protected void btnPDF_Click222(object sender, EventArgs e) { string downloadName = "Report"; byte[] downloadBytes = null; downloadName += ".pdf"; PdfConverter pdfConverter = new PdfConverter(); pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4; pdfConverter.PdfStandardSubset = PdfStandardSubset.Full; pdfConverter.PdfDocumentOptions.AutoSizePdfPage = true; pdfConverter.PdfDocumentOptions.EmbedFonts = true; pdfConverter.PdfDocumentOptions.BottomMargin = 80; pdfConverter.PdfDocumentOptions.TopMargin = 50; string url = string.Format("http://{0}/ExamOnline/ExamPaperStorage/ExamPaperView.aspx?epid=39&isPdf=1", Request.Url.Host); downloadBytes = pdfConverter.GetPdfBytesFromUrl(url); 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(); }
public static Byte[] GetPdfContractFromHtml(string url) { PdfConverter pdfConverter = new PdfConverter(); pdfConverter.LicenseKey = Resource.License; pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4; pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal; pdfConverter.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Portrait; pdfConverter.PdfDocumentOptions.ShowHeader = false; pdfConverter.PdfDocumentOptions.ShowFooter = false; pdfConverter.PdfDocumentOptions.SinglePage = true; pdfConverter.PdfDocumentOptions.FitHeight = true; pdfConverter.PdfDocumentOptions.FitWidth = true; pdfConverter.PdfDocumentOptions.FitWidth = false; pdfConverter.PdfDocumentOptions.EmbedFonts = false; pdfConverter.PdfDocumentOptions.LiveUrlsEnabled = true; pdfConverter.PdfDocumentOptions.JpegCompressionEnabled = true; pdfConverter.ConversionDelay = 0; pdfConverter.ScriptsEnabled = true; pdfConverter.RightToLeftEnabled = true; byte[] pdfBytes = pdfConverter.GetPdfBytesFromUrl(url); //if (System.IO.File.Exists("C:\\Users\\edward.silva\\Desktop\\aTestFile.pdf")) // System.IO.File.Delete("C:\\Users\\edward.silva\\Desktop\\aTestFile.pdf"); //using (FileStream fs = System.IO.File.Create("C:\\Users\\edward.silva\\Desktop\\aTestFile.pdf")) //{ // fs.Write(pdfBytes, 0, (int)pdfBytes.Length); //} return(pdfBytes); }
protected void btnConvert_Click(object sender, EventArgs e) { PdfConverter pdfConverter = new PdfConverter(); // set the license key - required pdfConverter.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; // the URL of the HTML document to convert string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri; string htmlTableFilePath = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/HtmlTable/table_with_repeated_head.html"; // call the converter byte[] pdfBytes = pdfConverter.GetPdfBytesFromUrl(htmlTableFilePath); // 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"); httpResponse.AddHeader("Content-Disposition", String.Format("attachment; filename=RepeatedTableHead.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(); }
protected void btnConvert_Click(object sender, EventArgs e) { PdfConverter pdfConverter = new PdfConverter(); // set the license key pdfConverter.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; // set user and owner passwords pdfConverter.PdfSecurityOptions.UserPassword = "******"; pdfConverter.PdfSecurityOptions.OwnerPassword = "******"; // restrict the right to print and to copy the document content pdfConverter.PdfSecurityOptions.CanPrint = false; pdfConverter.PdfSecurityOptions.CanCopyContent = false; // call the converter byte[] pdfBytes = pdfConverter.GetPdfBytesFromUrl(textBoxWebPageURL.Text.Trim()); // 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"); httpResponse.AddHeader("Content-Disposition", String.Format("attachment; filename=PdfSecurity.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(); }
public ActionResult Index() { return View(); PdfConverter pdf = new PdfConverter(); byte[] bytes = pdf.GetPdfBytesFromUrl("http://localhost:53559/ModelosDeProposta/"); return File(bytes, "application/pdf", "arquivo.pdf"); }
public void Genratepdftext(string url) { try { string temp_path = ""; PdfConverter pdfobj = new PdfConverter(); string temp1 = ""; pdfobj.LicenseKey = "eVJIWUtLWUtZTFdJWUpIV0hLV0BAQEA="; pdfobj.PdfDocumentOptions.ShowHeader = false; pdfobj.PdfDocumentOptions.ShowFooter = false; pdfobj.PdfDocumentInfo.AuthorName = "Cyber Best Technologies"; pdfobj.PdfDocumentInfo.Title = "Pharmacy Board"; pdfobj.PdfDocumentInfo.Subject = "Certificate"; if (Convert.ToInt32(Request.QueryString[0].ToString().Substring(1)) < 11 || Convert.ToInt32(Request.QueryString[0].ToString().Substring(1)) > 19) { 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; } else { float width = (11f / 1.0f) * 72f; float height = (8.50f / 1.0f) * 72f; pdfobj.PdfDocumentOptions.AutoSizePdfPage = false; pdfobj.PdfDocumentOptions.PdfPageSize = PdfPageSize.Custom; pdfobj.PdfDocumentOptions.CustomPdfPageSize = new SizeF(width, height); pdfobj.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Landscape; } //pdfobj.PdfDocumentInfo.Keywords = "HTML, PDF,Converter"; pdfobj.PdfDocumentInfo.CreatedDate = DateTime.Now; byte[] downloadBytes = pdfobj.GetPdfBytesFromUrl(url); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); // response.Flush(); response.AddHeader("Content-Type", "binary/octet-stream"); response.AddHeader("Content-Disposition", "attachment; filename=" + pname() + ".pdf; size=" + downloadBytes.Length.ToString()); response.BinaryWrite(downloadBytes); PersonLicensing.Utilities_Licensing.GetCertficateJournal(Request.QueryString["refid"], pname().Replace("_", " "), Session["UID"].ToString()); // response.Flush(); // response.End(); } catch (Exception EX) { //return ""; throw EX; } }
private void ConvertURLToPDF(string pUrl, string pfileName, bool pEnviarEmail) { string urlToConvert = pUrl;// textBoxWebPageURL.Text.Trim(); // 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 - required pdfConverter.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; pdfConverter.EvoInternalFileName = ConfigurationManager.AppSettings["pathEvoInternal"].ToString(); // set the converter options - optional pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4; pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.NoCompression; pdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Landscape; // set if header and footer are shown in the PDF - optional - default is false pdfConverter.PdfDocumentOptions.ShowHeader = false; ////cbAddHeader.Checked; pdfConverter.PdfDocumentOptions.ShowFooter = false; // cbAddFooter.Checked; // set if the HTML content is resized if necessary to fit the PDF page width - default is true //pdfConverter.PdfDocumentOptions.FitWidth = true;// cbFitWidth.Checked; //pdfConverter.PdfDocumentOptions.StretchToFit = true; pdfConverter.PdfDocumentOptions.AutoSizePdfPage = false; //pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize. pdfConverter.PdfDocumentOptions.RightMargin = 5; // set the embedded fonts option - optional - default is false pdfConverter.PdfDocumentOptions.EmbedFonts = false; // cbEmbedFonts.Checked; // set the live HTTP links option - optional - default is true pdfConverter.PdfDocumentOptions.LiveUrlsEnabled = false; // cbLiveLinks.Checked; // set if the JavaScript is enabled during conversion to a PDF - default is true pdfConverter.JavaScriptEnabled = true;// cbClientScripts.Checked; // set if the images in PDF are compressed with JPEG to reduce the PDF document size - default is true pdfConverter.PdfDocumentOptions.JpegCompressionEnabled = true;// cbJpegCompression.Checked; pdfConverter.ConversionDelay = 5; // be saved to a file or sent as a browser response byte[] pdfBytes = pdfConverter.GetPdfBytesFromUrl(urlToConvert); this.Response.Clear(); this.Response.ContentType = "text/pdf"; this.Response.ContentEncoding = Encoding.GetEncoding("iso-8859-1"); this.Response.Charset = "iso-8859-1"; this.Response.AddHeader("content-disposition", "attachment;filename=RelatorioDeNotasDeCorretagem.csv"); //this.Response.Write(lBuilder.ToString()); this.Response.End(); }
private void btnCreatePdf_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; try { PdfConverter pdfConverter = new PdfConverter(); // set the license key pdfConverter.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; // We convert the HTML page as local disk file because IIS and VS WebDev Server // don't have .svg included in MIME types by default. // When converting HTML pages from an IIS server the MIME type image/svg+xml // must be added to IIS in order to serve the .svg files referenced in HTML string htmlWithSvgFilePath = System.IO.Path.Combine(Application.StartupPath, @"..\..\SVG\svg.html"); // SVG can be used inline in a XML document string xmlWithInlineSvgFilePath = System.IO.Path.Combine(Application.StartupPath, @"..\..\SVG\svginline.xml"); this.Cursor = Cursors.WaitCursor; // save the PDF bytes in a file on disk string outFilePath = System.IO.Path.Combine(Application.StartupPath, "SvgToPdf.pdf"); try { // call the converter byte[] pdfBytes = pdfConverter.GetPdfBytesFromUrl(htmlWithSvgFilePath); System.IO.File.WriteAllBytes(outFilePath, pdfBytes); } finally { this.Cursor = Cursors.Arrow; } // open the generated PDF document in an external viewer DialogResult dr = MessageBox.Show("Open the rendered file in an external viewer?", "Open Rendered File", MessageBoxButtons.YesNo); if (dr == DialogResult.Yes) { System.Diagnostics.Process.Start(outFilePath); } } catch (Exception ex) { MessageBox.Show(ex.Message); return; } finally { this.Cursor = Cursors.Arrow; } }
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 = 120; 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.GetPdfBytesFromUrl(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(); }
private void btnConvert_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; try { PdfConverter pdfConverter = new PdfConverter(); // set the license key pdfConverter.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; // the URL of the HTML table with repeated header string htmlTableFilePath = System.IO.Path.Combine(Application.StartupPath, @"..\..\HtmlTable\table_with_repeated_head.html"); this.Cursor = Cursors.WaitCursor; // save the PDF bytes in a file on disk string outFilePath = System.IO.Path.Combine(Application.StartupPath, "RepeatedTableHead.pdf"); try { // call the converter byte[] pdfBytes = pdfConverter.GetPdfBytesFromUrl(htmlTableFilePath); System.IO.File.WriteAllBytes(outFilePath, pdfBytes); } finally { this.Cursor = Cursors.Arrow; } // open the generated PDF document in an external viewer DialogResult dr = MessageBox.Show("Open the rendered file in an external viewer?", "Open Rendered File", MessageBoxButtons.YesNo); if (dr == DialogResult.Yes) { System.Diagnostics.Process.Start(outFilePath); } } catch (Exception ex) { MessageBox.Show(ex.Message); return; } finally { this.Cursor = Cursors.Arrow; } }
public static byte[] ToPdfBytes(string urlToConvert, PdfPageOrientation pageOrientation = PdfPageOrientation.Portrait) { // 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 - required pdfConverter.LicenseKey = "1f7n9ebm9eTl5uP15vvl9ebk++Tn++zs7Ow="; // set the converter options - optional pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4; pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Best; pdfConverter.PdfDocumentOptions.PdfPageOrientation = pageOrientation; pdfConverter.PdfDocumentOptions.TopMargin = 20; pdfConverter.PdfDocumentOptions.BottomMargin = 20; // set if the HTML content is resized if necessary to fit the PDF page width - default is true pdfConverter.PdfDocumentOptions.FitWidth = true; // set the embedded fonts option - optional - default is false pdfConverter.PdfDocumentOptions.EmbedFonts = true; // set if the JavaScript is enabled during conversion to a PDF - default is true pdfConverter.JavaScriptEnabled = true; // set if the images in PDF are compressed with JPEG to reduce the PDF document size - default is true pdfConverter.PdfDocumentOptions.JpegCompressionEnabled = true; pdfConverter.PdfDocumentOptions.LiveUrlsEnabled = false; pdfConverter.PdfDocumentOptions.InternalLinksEnabled = true; pdfConverter.ConversionDelay = 1; // Performs the conversion and get the pdf document bytes that can // be saved to a file or sent as a browser response return(pdfConverter.GetPdfBytesFromUrl(urlToConvert)); }
protected void btnConvert_Click(object sender, EventArgs e) { PdfConverter pdfConverter = new PdfConverter(); // set the license key - required pdfConverter.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; /*// convert a XML document with inline SVG string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri; string htmlWithSvgUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/SVG/svginline.xml";*/ // We convert the HTML page as local disk file because IIS and VS WebDev Server // don't have .svg included in MIME types by default. // When converting HTML pages from an IIS server the MIME type image/svg+xml // must be added to IIS in order to serve the .svg files referenced in HTML string htmlWithSvgUrl = System.IO.Path.Combine(Server.MapPath("~"), @"SVG\svg.html"); // call the converter byte[] pdfBytes = pdfConverter.GetPdfBytesFromUrl(htmlWithSvgUrl); // 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"); httpResponse.AddHeader("Content-Disposition", String.Format("attachment; filename=SvgToPdf.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(); }
protected void btnConvert_Click(object sender, EventArgs e) { PdfConverter pdfConverter = new PdfConverter(); // set the license key pdfConverter.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; // show header and footer in the rendered PDF pdfConverter.PdfDocumentOptions.ShowHeader = true; pdfConverter.PdfDocumentOptions.ShowFooter = true; // set the header height in points pdfConverter.PdfHeaderOptions.HeaderHeight = 60; string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri; string headerAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/HeaderFooter/HeaderAndFooterHtml.htm"; // set the header HTML area HtmlToPdfElement headerHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfHeaderOptions.HeaderHeight, headerAndFooterHtmlUrl, 1024, 0); headerHtml.FitHeight = true; pdfConverter.PdfHeaderOptions.AddElement(headerHtml); // set the footer height in points pdfConverter.PdfFooterOptions.FooterHeight = 60; //write the page number TextElement footerTextElement = new TextElement(0, 30, "This is page &p; of &P; ", new Font(new FontFamily("Times New Roman"), 10, GraphicsUnit.Point)); footerTextElement.TextAlign = HorizontalTextAlign.Right; pdfConverter.PdfFooterOptions.AddElement(footerTextElement); // set the footer HTML area HtmlToPdfElement footerHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfFooterOptions.FooterHeight, headerAndFooterHtmlUrl, 1024, 0); footerHtml.FitHeight = true; pdfConverter.PdfFooterOptions.AddElement(footerHtml); if (!cbAlternateHeaderAndFooter.Checked) { // Performs the conversion and get the pdf document bytes that can // be saved to a file or sent as a browser response byte[] pdfBytes = pdfConverter.GetPdfBytesFromUrl(textBoxWebPageURL.Text); // 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"); httpResponse.AddHeader("Content-Disposition", String.Format("attachment; filename=HtmlInHeaderAndFooter.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(); } else { // set an alternate header and footer on the even pages // call the converter and get a Document object from URL Document pdfDocument = pdfConverter.GetPdfDocumentObjectFromUrl(textBoxWebPageURL.Text); if (pdfDocument.Pages.Count >= 2) { // get the alternate header and footer width and height // the width is given by the PDF page width float altHeaderFooterWidth = pdfDocument.Pages[0].ClientRectangle.Width; // the height is the same with the document header height from the PdfConverter object float altHeaderHeight = pdfConverter.PdfHeaderOptions.HeaderHeight; float altFooterHeight = pdfConverter.PdfFooterOptions.FooterHeight; // create the alternate header template Template altHeaderTemplate = pdfDocument.Templates.AddNewTemplate(altHeaderFooterWidth, altHeaderHeight); string alternateHeaderAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/HeaderFooter/HeaderAndFooterHtml2.htm"; // add html to the header HtmlToPdfElement altHeaderHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfHeaderOptions.HeaderHeight, alternateHeaderAndFooterHtmlUrl, 1024, 0); altHeaderHtml.FitHeight = true; altHeaderTemplate.AddElement(altHeaderHtml); // add a horizontal line to the bottom of the header LineElement headerLine = new LineElement(0, altHeaderHeight, altHeaderFooterWidth, altHeaderHeight); altHeaderTemplate.AddElement(headerLine); // add page numbering to the left of the header PdfFont pageNumberFont = pdfDocument.Fonts.Add(new Font(new FontFamily("Times New Roman"), 10, GraphicsUnit.Point)); TextElement pageNumbering = new TextElement(10, 10, "Page &p; of &P;", pageNumberFont, Color.Blue); altHeaderTemplate.AddElement(pageNumbering); // create the alternate footer template Template altFooterTemplate = pdfDocument.Templates.AddNewTemplate(altHeaderFooterWidth, altFooterHeight); // add html to the footer HtmlToPdfElement altFooterHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfHeaderOptions.HeaderHeight, alternateHeaderAndFooterHtmlUrl, 1024, 0); altFooterHtml.FitHeight = true; altFooterTemplate.AddElement(altFooterHtml); for (int pageIndex = 1; pageIndex < pdfDocument.Pages.Count; pageIndex += 2) { PdfPage pdfPage = pdfDocument.Pages[pageIndex]; pdfPage.Header = altHeaderTemplate; pdfPage.Footer = altFooterTemplate; } } byte[] pdfBytes = null; try { pdfBytes = pdfDocument.Save(); } finally { // close the Document to realease all the resources pdfDocument.Close(); } // 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"); httpResponse.AddHeader("Content-Disposition", String.Format("attachment; filename=HtmlInHeaderAndFooter.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(); } }
public long AddAccidentalClaim(AccidentalClaimModel accidentalModel) { try { tblBooking tblBooking = db.tblBookings.FirstOrDefault(x => x.BookingId == Convert.ToInt32(accidentalModel.BookingId)); if (tblBooking != null) { tblBooking.IsAccidentalClaimRaised = new bool?(true); tblBooking.IsRenterRaisedDispute = new bool?(true); db.SaveChanges(); } } catch (Exception Ex) { } string tempPath = System.IO.Path.Combine(HostingEnvironment.MapPath("~/PdfTemplates"), "AccidentalClaimPDF.html"); string _pdfContent = System.IO.File.ReadAllText(tempPath); _pdfContent = _pdfContent.Replace("{fullname}", accidentalModel.FullName); _pdfContent = _pdfContent.Replace("{email}", accidentalModel.Email); _pdfContent = _pdfContent.Replace("{dob}", accidentalModel.DOB); _pdfContent = _pdfContent.Replace("{booking}", accidentalModel.BookingId); _pdfContent = _pdfContent.Replace("{address}", accidentalModel.Address); _pdfContent = _pdfContent.Replace("{postcode}", accidentalModel.PostCode); _pdfContent = _pdfContent.Replace("{mobilenumber}", accidentalModel.MobileNumber); _pdfContent = _pdfContent.Replace("{dateofincident}", accidentalModel.DateOfIncident); _pdfContent = _pdfContent.Replace("{timeofincident}", accidentalModel.TimeOfIncident); _pdfContent = _pdfContent.Replace("{incharge}", accidentalModel.InCharge); _pdfContent = _pdfContent.Replace("{incidentdetails}", accidentalModel.IncidentDescription); _pdfContent = _pdfContent.Replace("{witnessdetails}", accidentalModel.WitnessDetails); _pdfContent = _pdfContent.Replace("{thirdpartydetails}", accidentalModel.ThirdPartyDetails); _pdfContent = _pdfContent.Replace("{reportedtopolice}", accidentalModel.IsReportedToPolice == true ? "Yes" : "No"); _pdfContent = _pdfContent.Replace("{anotherinsurer}", accidentalModel.IsAnotherInsurer == true ? "Yes" : "No"); _pdfContent = _pdfContent.Replace("{refused}", accidentalModel.IsRefusedRenewal == true ? "Yes" : "No"); _pdfContent = _pdfContent.Replace("{itemclaims}", accidentalModel.ItemsClaimedFor); _pdfContent = _pdfContent.Replace("{circumstances}", accidentalModel.Circumstances); _pdfContent = _pdfContent.Replace("{previousinsurer}", accidentalModel.PreviousInsurerName); _pdfContent = _pdfContent.Replace("{expirydate}", accidentalModel.ExpiryDate); _pdfContent = _pdfContent.Replace("{pastclaims}", accidentalModel.PastClaimDetails); _pdfContent = _pdfContent.Replace("{criminalconvictions}", accidentalModel.IsAnyCriminalConviction == true ? "Yes" : "No"); _pdfContent = _pdfContent.Replace("{policycancelled}", accidentalModel.IsPolicyCancelled == true ? "Yes" : "No"); _pdfContent = _pdfContent.Replace("{providedetails}", accidentalModel.ProvidedDetails); TextWriter _fWriter = new StreamWriter(HostingEnvironment.MapPath("~/Templates/dfTemplate.htm")); _fWriter.Write(_pdfContent); _fWriter.Close(); _fWriter.Dispose(); PdfConverter pdfConverter = new PdfConverter(); pdfConverter.LicenseKey = "elFLWktaTE9IWk9USlpJS1RLSFRDQ0ND"; pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.Letter; pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.NoCompression; pdfConverter.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Landscape; pdfConverter.PdfDocumentOptions.BottomMargin = 20; pdfConverter.PdfDocumentOptions.TopMargin = 20; pdfConverter.PdfDocumentOptions.LeftMargin = 20; pdfConverter.PdfDocumentOptions.RightMargin = 20; pdfConverter.PdfDocumentOptions.ShowHeader = false; pdfConverter.PdfDocumentOptions.ShowFooter = false; pdfConverter.PdfDocumentOptions.AutoSizePdfPage = false; pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = true; pdfConverter.PdfDocumentOptions.SinglePage = true; byte[] pdfBytes = pdfConverter.GetPdfBytesFromUrl(HostingEnvironment.MapPath("~/Templates/dfTemplate.htm")); string pdfName = RandomString(7) + ".pdf"; accidentalModel.PDFName = pdfName; System.IO.File.WriteAllBytes(HostingEnvironment.MapPath("~/PdfTemplates/AccidentalClaimForms/" + pdfName), pdfBytes); Mapper.Initialize(new MapperConfigurationExpression() { AllowNullCollections = true, AllowNullDestinationValues = true, CreateMissingTypeMaps = true }); tblAccidentalClaim accidental = Mapper.Instance.Map<tblAccidentalClaim>(accidentalModel); accidental.IsApproved = false; accidental.CreatedDate = DateTime.Now; db.tblAccidentalClaims.Add(accidental); db.SaveChanges(); return accidental.Id; }
//public ActionResult ReportPdf(Guid id, int? challengeId) //{ public ActionResult ReportPdf(int id, int? SelectedOrderBy = null, int? SelectedChallengeStatus = null, string SelectedSuburb = "Suburb", string SearchString = "", int? timeRange = null, int page = 1, int pageSize = 0) { var membershipUser = Membership.GetUser(); bool? Status = null; switch (SelectedChallengeStatus) { case 1: Status = true; break; case 2: Status = false; break; case 0: Status = null; break; } if (membershipUser != null && membershipUser.ProviderUserKey != null) { bool InInstance = new ChallengesAdminService().CheckInInstance(id, (Guid)membershipUser.ProviderUserKey); if (LayoutViewModel.IsCouncil) { if (InInstance) { var pdfConverter = new PdfConverter(); pdfConverter.LicenseKey = "Zk1URlVVRldTXlVGVUhWRlVXSFdUSF9fX18="; pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4; pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal; pdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait; pdfConverter.HtmlViewerWidth = 800; var url = Url.Action("ReportHtml", "ChallengesAdmin", new RouteValueDictionary(new { id, SelectedChallengeStatus, Status, SelectedSuburb, SearchString, timeRange, page, pageSize }), "http", Request.Url.Host); try { var bytes = pdfConverter.GetPdfBytesFromUrl(url); return File(bytes, "application/pdf"); } catch (Exception) { return RedirectToAction("ReportHtml", new { id, SelectedChallengeStatus, Status, SelectedSuburb, SearchString, timeRange, page, pageSize }); } } else return RedirectToAction("Index", "ChallengesAdmin"); } else return RedirectToAction("Index", "Home"); } else return RedirectToAction("Index", "Home"); }
/// <summary> /// Convert the HTML code from the specified URL to a PDF document and send the /// document to the browser /// </summary> private void ConvertURLToPDF() { string urlToConvert = textBoxWebPageURL.Text.Trim(); // 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 - required pdfConverter.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; // set the converter options - optional 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 HTML selectors (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); // optionally wait for asynchronous items pdfConverter.ConversionDelay = 2; // Performs the conversion and get the pdf document bytes that can // be saved to a file or sent as a browser response byte[] pdfBytes = pdfConverter.GetPdfBytesFromUrl(urlToConvert); // 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(); }
private void DownLoadPDF() { string url = string.Format("http://{0}/ExamOnline/ExamPaperStorage/ExamPaperView.aspx?epid={1}&isPdf=1", Request.Url.Host, RequestEPID); #region Cookies添加 //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl); //request.Credentials = CredentialCache.DefaultCredentials; //request.Headers.Add("Cookie", Request.Headers["Cookie"]); //request.CookieContainer = new CookieContainer(); ////string strCookieFilter = ".ASPXAUTH,BitAutoLogId,BitAutoUserCode,ASP.NET_SessionId,mmploginusername"; //string strCookieFilter = "BitAutoLogId,BitAutoUserCode,ASP.NET_SessionId,mmploginusername"; //HttpCookieCollection oCookies = Context.Request.Cookies; //for (int j = 0; j < oCookies.Count; j++) //{ // HttpCookie oCookie = oCookies.Get(j); // if (strCookieFilter.IndexOf(oCookie.Name) > -1) // { // Cookie oC = new Cookie(); // // Convert between the System.Net.Cookie to a System.Web.HttpCookie... // oC.Domain = Context.Request.Url.Host; // myRequest.RequestUri.Host; // oC.Expires = oCookie.Expires; // oC.Name = oCookie.Name; // oC.Path = oCookie.Path; // oC.Secure = oCookie.Secure; // oC.Value = oCookie.Value.Replace(",", "%2C"); // request.CookieContainer.Add(oC); // } //} //var s = request.GetResponse(); //var r = new StreamReader(s.GetResponseStream(), Encoding.UTF8); //var htmlText = r.ReadToEnd(); //htmlText = htmlText.Replace("<input name=", "<span name="); //htmlText = htmlText.Replace("<div class=\"taskT\">试卷查看</div>", ""); #endregion byte[] downloadBytes = new byte[] { }; string downloadName = "网页版试卷.pdf"; try { PdfConverter pdfConverter = GetPdfConvert(); //var downloadBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlText); //var downloadBytes = pdfConverter.GetPdfBytesFromUrl("http://ncc.sys1.bitauto.com/AjaxServers/ExamOnline/tt.htm"); downloadBytes = pdfConverter.GetPdfBytesFromUrl(url); } catch (Exception ex) { downloadBytes = new byte[] { }; BLL.Loger.Log4Net.Info("在页面ExamPaperPDF.aspx 报错:" + ex.Message); } 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(); }
public static byte[] PrintToPDFByUrl(string url) { byte[] pdfBytes = null; try { //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 = false; pdfConverter.PdfDocumentOptions.ShowFooter = false; pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = true; pdfConverter.PdfDocumentOptions.FitWidth = true; pdfConverter.PdfDocumentOptions.EmbedFonts = false; pdfConverter.PdfDocumentOptions.LiveUrlsEnabled = true; //pdfConverter.PdfDocumentOptions.LeftMargin = 15; //pdfConverter.PdfDocumentOptions.RightMargin = 15; pdfConverter.ScriptsEnabled = true; pdfConverter.ActiveXEnabled = true; pdfConverter.PageWidth = 840; //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"; //byte[] pdfBytes = null; pdfBytes = pdfConverter.GetPdfBytesFromUrl(url); //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 { } return pdfBytes; }
/// <summary> /// Convert the HTML code from the specified URL to a PDF document /// and send the document to the browser /// </summary> private void ConvertURLToPDF(HttpContext pContext, string pUrl, string pfileName, bool pEnviarEmail) { string urlToConvert = pUrl;// textBoxWebPageURL.Text.Trim(); // 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 - required pdfConverter.LicenseKey = "ORIJGQoKGQkZCxcJGQoIFwgLFwAAAAA="; // set the converter options - optional pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4; pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.NoCompression; pdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Landscape; // set if header and footer are shown in the PDF - optional - default is false pdfConverter.PdfDocumentOptions.ShowHeader = false; ////cbAddHeader.Checked; pdfConverter.PdfDocumentOptions.ShowFooter = false; // cbAddFooter.Checked; // set if the HTML content is resized if necessary to fit the PDF page width - default is true //pdfConverter.PdfDocumentOptions.FitWidth = true;// cbFitWidth.Checked; //pdfConverter.PdfDocumentOptions.StretchToFit = true; pdfConverter.PdfDocumentOptions.AutoSizePdfPage = false; //pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize. pdfConverter.PdfDocumentOptions.RightMargin = 5; // set the embedded fonts option - optional - default is false pdfConverter.PdfDocumentOptions.EmbedFonts = false; // cbEmbedFonts.Checked; // set the live HTTP links option - optional - default is true pdfConverter.PdfDocumentOptions.LiveUrlsEnabled = false; // cbLiveLinks.Checked; // set if the JavaScript is enabled during conversion to a PDF - default is true pdfConverter.JavaScriptEnabled = true;// cbClientScripts.Checked; // set if the images in PDF are compressed with JPEG to reduce the PDF document size - default is true pdfConverter.PdfDocumentOptions.JpegCompressionEnabled = true;// cbJpegCompression.Checked; pdfConverter.ConversionDelay = 5; // be saved to a file or sent as a browser response byte[] pdfBytes = pdfConverter.GetPdfBytesFromUrl(urlToConvert); // send the PDF document as a response to the browser for download if (pEnviarEmail) { MemoryStream ms = new MemoryStream(pdfBytes); ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf); Attachment attach = new System.Net.Mail.Attachment(ms, ct); attach.ContentDisposition.FileName = pfileName; attach.ContentDisposition.DispositionType = String.Format("attachment; filename={0}; size={1}", pfileName, pdfBytes.Length.ToString()); attach.ContentDisposition.CreationDate = DateTime.Now; MailMessage pMail = new MailMessage(); pMail.From = new MailAddress("*****@*****.**"); pMail.To.Add("*****@*****.**"); //pMail.To.Add(req.EmailCliente); pMail.To.Add("*****@*****.**"); pMail.Subject = "Invixx - Extrato Consolidado"; pMail.IsBodyHtml = false; pMail.Body = @"Prezado Cliente. Segue anexo o seu extrato consolidado. Atenciosamente Invixx"; pMail.Attachments.Add(attach); SmtpClient pSmtpClient = new SmtpClient("ironport.gradual.intra"); System.Net.NetworkCredential credential = new System.Net.NetworkCredential("amiguel", "Gradual456", "GRADUAL"); pSmtpClient.Credentials = credential; pSmtpClient.Send(pMail); pContext.Response.Clear(); pContext.Response.Write("sucesso"); pContext.Response.End(); } else { pContext.Response.Clear(); pContext.Response.ContentType = "application/pdf"; pContext.Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}; size={1}", pfileName, pdfBytes.Length.ToString())); pContext.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 pContext.Response.End(); } }
public byte[] ConvertURLToPDF(string URI) { string urlToConvert = URI; // 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 - required pdfConverter.LicenseKey = "QGtxYHNzYHF2dXNgc25wYHNxbnFybnl5eXk="; // set the converter options - optional 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 HTML selectors (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 saved to a file or sent as a browser response byte[] pdfBytes = pdfConverter.GetPdfBytesFromUrl(urlToConvert); //return pdfBytes; //send the PDF document as a response to the browser for download System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.AddHeader("Content-Type", "application/pdf"); //if (radioAttachment.Checked) // response.AddHeader("Content-Disposition", String.Format("attachment; filename=GettingStarted.pdf; size={0}", pdfBytes.Length.ToString())); //else // response.AddHeader("Content-Disposition", String.Format("inline; filename=GettingStarted.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(); return pdfBytes; }
public ActionResult Voucher(Guid id, int? rewardId) { var pdfConverter = new PdfConverter(); pdfConverter.LicenseKey = "Zk1URlVVRldTXlVGVUhWRlVXSFdUSF9fX18="; pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4; pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal; pdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait; pdfConverter.HtmlViewerWidth = 800; //var url = Url.Action("VoucherHtml", "Rewards", new { id }); var url = Url.Action("VoucherHtml", "Rewards", new RouteValueDictionary(new { id = id, rewardId }), "http", Request.Url.Host); try { var bytes = pdfConverter.GetPdfBytesFromUrl(url); return File(bytes, "application/pdf"); } catch (Exception) { return RedirectToAction("VoucherHtml", new { id }); } }
protected void btnConvert_Click(object sender, EventArgs e) { MemoryStream pdfStream2 = null; try { PdfConverter pdfConverter = new PdfConverter(); // set the license key pdfConverter.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; // Convert the first document and produce a Document object containing the conversion result Document document1 = pdfConverter.GetPdfDocumentObjectFromUrl(textBoxWebPageURL1.Text); // Load a second document from a stream produced by the conversion of the second URL byte[] doc2Bytes = pdfConverter.GetPdfBytesFromUrl(textBoxWebPageURL2.Text); pdfStream2 = new MemoryStream(doc2Bytes); // Load a PDF document from a stream Document document2 = new Document(pdfStream2); // Append second to the first document document1.AppendDocument(document2); // Convert the third URL to PDF and obtain a PDF document object Document document3 = pdfConverter.GetPdfDocumentObjectFromUrl(textBoxWebPageURL3.Text); // Append the third document after the second document1.AppendDocument(document3); // When AutoCloseAppendedDocs property is set on true the appended documents are automatically closed // when the document to which they are appended is closed document1.AutoCloseAppendedDocs = true; byte[] pdfBytes = null; try { pdfBytes = document1.Save(); } finally { // Close the Document to realease all the resources // The appended document3 will be automatically closed also document1.Close(); } // 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"); httpResponse.AddHeader("Content-Disposition", String.Format("attachment; filename=HtmlToPdfFeatures.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(); } finally { if (pdfStream2 != null) pdfStream2.Close(); } }
private void btnConvertMerge_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; MemoryStream pdfStream2 = null; try { PdfConverter pdfConverter = new PdfConverter(); // set the license key pdfConverter.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; // Convert the first document and produce a Document object containing the conversion result Document document1 = pdfConverter.GetPdfDocumentObjectFromUrl(textBoxURL1.Text); // Load a second document from a stream produced by the conversion of the second URL byte[] doc2Bytes = pdfConverter.GetPdfBytesFromUrl(textBoxURL2.Text); pdfStream2 = new MemoryStream(doc2Bytes); // Load a PDF document from a stream Document document2 = new Document(pdfStream2); // Append second to the first document document1.AppendDocument(document2); // Convert the third URL to PDF and obtain a PDF document object Document document3 = pdfConverter.GetPdfDocumentObjectFromUrl(textBoxURL3.Text); // Append the third document after the second document1.AppendDocument(document3); // When AutoCloseAppendedDocs property is set on true the appended documents are automatically closed // when the document to which they are appended is closed document1.AutoCloseAppendedDocs = true; string outFilePath = Path.Combine(Application.StartupPath, "AppendDocument.pdf"); try { document1.Save(outFilePath); } finally { // Close the Document to realease all the resources // The appended document2 and document3 will be automatically closed document1.Close(); } DialogResult dr = MessageBox.Show("Open the rendered file in an external viewer?", "Open Rendered File", MessageBoxButtons.YesNo); if (dr == DialogResult.Yes) { System.Diagnostics.Process.Start(outFilePath); } } catch (Exception ex) { MessageBox.Show(ex.Message); return; } finally { // close the memory stream if (pdfStream2 != null) pdfStream2.Close(); this.Cursor = Cursors.Arrow; } }
public void ProcessRequest(HttpContext context) { var response = context.Response; var queryString = context.Request.QueryString; if (queryString["url"] == null) { response.StatusCode = 400; response.End(); return; } var url = queryString["url"]; // Create the PDF converter. Optionally the HTML viewer width can be specified as parameter // The default HTML viewer width is 1024 pixels. var pdfConverter = new PdfConverter(); // set the license key - required pdfConverter.LicenseKey = ConfigurationManager.AppSettings["EvoPdfLicense"] ?? "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; // set the converter options - optional 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 HTML selectors (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 saved to a file or sent as a browser response var pdfBytes = pdfConverter.GetPdfBytesFromUrl(url); // send the generated PDF document to client browser // add the Content-Type and Content-Disposition HTTP headers response.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 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(); }
public string SaveTheftClaim(TheftClaimModel model) { string path = Path.Combine(HttpContext.Current.Server.MapPath("~/PdfTemplates"), "TheftClaimPDF.html"); model.FullName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(model.FullName.ToLower()); int bookingid; try { bookingid = Convert.ToInt32(model.BookingId); } catch (Exception ex) { bookingid = 0; } tblBooking tblBooking = ((IQueryable <tblBooking>) this._dbEntity.tblBookings).FirstOrDefault <tblBooking>((Expression <Func <tblBooking, bool> >)(x => x.BookingId == (long)bookingid)); if (tblBooking != null) { tblBooking.IsTheftClaimRaised = new bool?(true); tblBooking.IsRenterRaisedDispute = new bool?(true); this._dbEntity.SaveChanges(); } string str1 = System.IO.File.ReadAllText(path).Replace("{fullname}", model.FullName).Replace("{email}", model.Email); string oldValue1 = "{dob}"; DateTime dateTime = model.DOB.Date; string newValue1 = dateTime.ToString("MM-dd-yyyy"); string str2 = str1.Replace(oldValue1, newValue1).Replace("{booking}", model.BookingId).Replace("{address}", model.Address).Replace("{postcode}", model.PostCode).Replace("{mobilenumber}", model.MobileNumber).Replace("{circumstances}", model.Circumstances).Replace("{stolenlist}", model.ListOfStolenItems).Replace("{approxvalue}", "£ " + model.ApproxValue).Replace("{responsible}", model.WhoWasResponsible).Replace("{unattended}", model.HowLongUnattended); string oldValue2 = "{lastseen}"; dateTime = model.TimeAndDateLastSeen; string newValue2 = dateTime.ToString(); string str3 = str2.Replace(oldValue2, newValue2); string oldValue3 = "{discovered}"; dateTime = model.TimeAndDateTheftDiscovered; string newValue3 = dateTime.ToString(); string str4 = str3.Replace(oldValue3, newValue3); bool? nullable = model.IsAnyWitness; bool flag1 = true; string str5 = ((nullable.GetValueOrDefault() == flag1 ? (nullable.HasValue ? 1 : 0) : 0) == 0 ? str4.Replace("{anywitness}", "No").Replace("{witnessdetails}", string.Empty) : str4.Replace("{anywitness}", "Yes").Replace("{witnessdetails}", model.WitnessDetails)).Replace("{policecontact}", model.PoliceContactNumber).Replace("{crimeincident}", model.CrimeIncidentNumber); string str6 = !model.IsPoliceAttend ? str5.Replace("{policeattend}", "No") : str5.Replace("{policeattend}", "Yes"); string str7 = (!model.IsReportedToPoliceImmediately ? str6.Replace("{policeimmediately}", "No").Replace("{reasonforpolice}", model.ReasonForNotReportedImmediately) : str6.Replace("{policeimmediately}", "Yes").Replace("{reasonforpolice}", string.Empty)).Replace("{howsecured}", model.HowBicycleWasSecured).Replace("{locksecured}", model.DetailOfSecuredLock).Replace("{howaccess}", model.HowAccessGained).Replace("{alternatesecurity}", model.AlternativeSecurityMethod); nullable = model.IsAnotherInsurer; bool flag2 = true; string str8 = ((nullable.GetValueOrDefault() == flag2 ? (nullable.HasValue ? 1 : 0) : 0) == 0 ? str7.Replace("{isanotherinsurer}", "No") : str7.Replace("{isanotherinsurer}", "Yes")).Replace("{previousinsurer}", model.PreviousInsurerName).Replace("{expirydate}", model.ExpiryDate).Replace("{anybicycleclaim}", model.PastClaimDetails); nullable = model.IsAnyCriminalConviction; bool flag3 = true; string str9 = (nullable.GetValueOrDefault() == flag3 ? (nullable.HasValue ? 1 : 0) : 0) == 0 ? str8.Replace("{iscriminal}", "No") : str8.Replace("{iscriminal}", "Yes"); nullable = model.IsPolicyCancelled; bool flag4 = true; string str10 = (nullable.GetValueOrDefault() == flag4 ? (nullable.HasValue ? 1 : 0) : 0) == 0 ? str9.Replace("{ispolicycancelled}", "No") : str9.Replace("{ispolicycancelled}", "Yes"); nullable = model.IsRefusedRenewal; bool flag5 = true; string str11 = ((nullable.GetValueOrDefault() == flag5 ? (nullable.HasValue ? 1 : 0) : 0) == 0 ? str10.Replace("{isrefusedrenewal}", "No") : str10.Replace("{isrefusedrenewal}", "Yes")).Replace("{provideddetails}", model.ProvidedDetails); StreamWriter streamWriter = new StreamWriter(HostingEnvironment.MapPath("~/Templates/dfTemplate.htm")); streamWriter.Write(str11); streamWriter.Close(); streamWriter.Dispose(); PdfConverter pdfConverter = new PdfConverter(); pdfConverter.LicenseKey = "elFLWktaTE9IWk9USlpJS1RLSFRDQ0ND"; pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.Letter; pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.NoCompression; pdfConverter.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Landscape; pdfConverter.PdfDocumentOptions.BottomMargin = 20; pdfConverter.PdfDocumentOptions.TopMargin = 20; pdfConverter.PdfDocumentOptions.LeftMargin = 20; pdfConverter.PdfDocumentOptions.RightMargin = 20; pdfConverter.PdfDocumentOptions.ShowHeader = false; pdfConverter.PdfDocumentOptions.ShowFooter = false; pdfConverter.PdfDocumentOptions.AutoSizePdfPage = false; pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = true; pdfConverter.PdfDocumentOptions.SinglePage = true; string str12 = RandomString(7) + ".pdf"; byte[] pdfBytesFromUrl = pdfConverter.GetPdfBytesFromUrl(HostingEnvironment.MapPath("~/Templates/dfTemplate.htm")); System.IO.File.WriteAllBytes(HostingEnvironment.MapPath("~/PdfTemplates/TheftClaimForms/" + str12 ?? ""), pdfBytesFromUrl); model.PDFName = str12; Mapper.Initialize(new MapperConfigurationExpression() { AllowNullCollections = true, AllowNullDestinationValues = true, CreateMissingTypeMaps = true }); tblTheftClaim tblTheftClaim = Mapper.Instance.Map <tblTheftClaim>(model); tblTheftClaim.IsApproved = new bool?(false); tblTheftClaim.CreatedDate = new DateTime?(DateTime.Now); this._dbEntity.tblTheftClaims.Add(tblTheftClaim); this._dbEntity.SaveChanges(); return("Success"); }