public static void Main(string[] args) { var model = new HtmlToPdfModel(); model.HTML = "<h3>Hello world!</h3>"; model.CSS = "h3{color:#f00;}"; HtmlToPdf.Convert(model); }
public async Task <IActionResult> ConvertHtmlToPdf([FromBody] HtmlToPdfModel model) { if (model == null || string.IsNullOrEmpty(model.Url) || string.IsNullOrEmpty(model.FileType)) { return(Ok(new { Success = false, Message = "Error of input data." })); } if (model.FileType.ToLower() == "pdf") { if (!Enum.TryParse <PaperType>(model.PaperType, true, out var paperType)) { return(Ok(new { Success = false, Message = "Error of input data." })); } if (!Enum.TryParse <PaperOrientation>(model.PaperOrientation, true, out var paperOrientation)) { paperOrientation = PaperOrientation.Portrait; } var dimension = (Dimension)null; if (paperType == PaperType.Custom) { if (model.PaperWidth == null || model.PaperHeight == null) { return(Ok(new { Success = false, Message = "Width and height of the document should be set." })); } else { dimension = new Dimension { Width = model.PaperWidth.Value, Height = model.PaperHeight.Value, UnitName = model.PaperUnitName }; } } try { var data = await _phantomJsService.ConvertHtmlToPdfAsync(model.Url, paperType, paperOrientation, dimension); return(File(data, "application/pdf", "File.pdf")); } catch (Exception e) { return(Ok(new { Success = false, e.Message })); } } else { if (!Enum.TryParse <ImageType>(model.ImageType, true, out var imageType)) { return(Ok(new { Success = false, Message = "Error of input data." })); } var dimension = (Dimension)null; if (model.ImageWidth != null && model.ImageHeight != null) { dimension = new Dimension { Width = model.ImageWidth.Value, Height = model.ImageHeight.Value, UnitName = "px" }; } else if (model.ImageWidth != null) { dimension = new Dimension { Width = model.ImageWidth.Value, UnitName = "px" }; } try { var data = await _phantomJsService.ConvertHtmlToImageAsync(model.Url, imageType, dimension); return(File(data, model.ImageType.ToLower() == "jpg" ? "application/jpeg" : "application/png", $"File.{model.ImageType.ToLower()}")); } catch (Exception e) { return(Ok(new { Success = false, e.Message })); } } }
public async Task <IActionResult> ExportOffer(Guid Id, string template) { var offer = await OfferRepository.FindAsync(Id); HtmlToPdfModel <OfferRenderViewModel> htmltopdfmodel = new HtmlToPdfModel <OfferRenderViewModel>(); var footercontent = await TemplateService.RenderTemplateAsync("Template/FooterTemplate", new Footer()); htmltopdfmodel.Name = "Offer"; htmltopdfmodel.FooterContent = footercontent; htmltopdfmodel.Pages = new List <HtmlToPdfPage>(); List <Match> alineas = Regex.Matches(offer.IndexContent, @"((<h1.*>)([\s\S])+?(?=<h1.*>)|((<h1.*>)([\s\S])+(<\/p>)))").ToList(); htmltopdfmodel.ViewModel = await FillViewModel(Id, new OfferRenderViewModel()); int pagenumbers = 5; foreach (var item in alineas) { MatchCollection header = Regex.Matches(item.ToString(), @"(?<=(<h1.*>))(.|\n)*?(?=<\/h1>)"); var newalinea = Regex.Replace(item.ToString(), @"((<h1.*>))(.|\n)*?(\/h1>)", ""); htmltopdfmodel.Pages = PdfExtensions.CheckAlinea(newalinea, pagenumbers, htmltopdfmodel.Pages, header); pagenumbers++; } var textpages = htmltopdfmodel.Pages.Count + 5; #region pages htmltopdfmodel.Pages.Add(new HtmlToPdfPage { Header = offer.ProjectName, Body = "", Type = HtmlToPdfPageType.FrontPage, Index = 1, }); htmltopdfmodel.Pages.Add(new HtmlToPdfPage { Header = "Vertrouwelijk", Body = "", Type = HtmlToPdfPageType.Preface, Index = 2 }); htmltopdfmodel.Pages.Add(new HtmlToPdfPage { Header = "", Body = "", Type = HtmlToPdfPageType.PrefaceInfo, Index = 3 }); htmltopdfmodel.Pages.Add(new HtmlToPdfPage { Header = "Begroting", Body = "", Type = HtmlToPdfPageType.Estimate, Index = textpages++ }); htmltopdfmodel.Pages.Add(new HtmlToPdfPage { Header = "Voor Akkoord", Body = "", Type = HtmlToPdfPageType.Agree, Index = textpages++ }); #endregion htmltopdfmodel.Pages.Add(PdfExtensions.CreateIndex(htmltopdfmodel.Pages)); string documentcontent = await TemplateService.RenderTemplateAsync("Template/" + template, htmltopdfmodel); byte[] output = ConverterService.Convert(new HtmlToPdfDocument() { Objects = { new ObjectSettings() { HtmlContent = documentcontent, } } }); Response.Clear(); offer.IsOpen = 1; Response.ContentType = "Application/pdf"; Response.Headers.Add("Content-Disposition", string.Format("Attachment;FileName=Offer_" + offer.ProjectName + ".pdf;")); Response.Headers.Add("Content-Length", output.Length.ToString()); await OfferRepository.SaveChangesAsync(); await Response.Body.WriteAsync(output, 0, output.Length); return(Redirect(nameof(Index))); }
public static void Convert(HtmlToPdfModel model) { try { if (model == null) { return; } Byte[] bytes; //Boilerplate iTextSharp setup here //Create a stream that we can write to, in this case a MemoryStream using (var stream = new MemoryStream()) { //Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF using (var doc = new Document()) { //Create a writer that's bound to our PDF abstraction and our stream using (var writer = PdfWriter.GetInstance(doc, stream)) { //Open the document for writing doc.Open(); //In order to read CSS as a string we need to switch to a different constructor //that takes Streams instead of TextReaders. //Below we convert the strings into UTF8 byte array and wrap those in MemoryStreams using (var cssStream = new MemoryStream(Encoding.UTF8.GetBytes(model.CSS))) { using (var htmlStream = new MemoryStream(Encoding.UTF8.GetBytes(model.HTML))) { var fontProvider = new XMLWorkerFontProvider(); if (!string.IsNullOrEmpty(model.FontPath) && !string.IsNullOrEmpty(model.FontName)) { fontProvider.Register(model.FontPath, model.FontName); //Parse the HTML with css font-family XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, htmlStream, cssStream, Encoding.UTF8, fontProvider); } else { //Parse the HTML without css font-family XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, htmlStream, cssStream); } } } doc.Close(); } } //After all of the PDF "stuff" above is done and closed but **before** we //close the MemoryStream, grab all of the active bytes from the stream bytes = stream.ToArray(); } //Now we just need to do something with those bytes. //Here I'm writing them to disk but if you were in ASP.Net you might Response.BinaryWrite() them. //You could also write the bytes to a database in a varbinary() column (but please don't) or you //could pass them to another function for further PDF processing. // use this line on Windows version //File.WriteAllBytes(model.OutputPath, bytes); // use these lines on Mac version string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "data"); path = Path.Combine(path, "test.pdf"); File.WriteAllBytes(path, bytes); } catch (Exception e) { throw e; } }