//generate PDF from HTML - thanks wkhtmltopdf and the shark.pdfconvert C# wapper private void generatePDF(string out_folder, string html_stream, string pdf_out, string error_file) { System.IO.Directory.CreateDirectory(out_folder); try { PdfConvert.Convert(new PdfConversionSettings { Title = "My Static Content", Content = html_stream, OutputPath = pdf_out }); } catch (Exception ex) { //File.AppendAllText(log_file, ex); using (StreamWriter writer = new StreamWriter(error_file, true)) { writer.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now.ToString() + Environment.NewLine + pdf_out); writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); } Exception_Count++; PropertyChanged(this, new PropertyChangedEventArgs("Exception_Count")); } }
static void Main(string[] args) { var currentDirectory = Directory.GetCurrentDirectory(); var templateFile = File.ReadAllText($"{currentDirectory}/basetemplate.html"); var pets = new List <Pet> { new Pet { Name = "Kira" }, new Pet { Name = "Kaiser" }, new Pet { Name = "Keitty" } }; var template = Template.Parse(templateFile); var result = template.Render(new { Pets = pets }).ToString(); PdfConvert.Convert(new PdfConversionSettings { Title = "My Static Content", Content = result, OutputPath = @"E:\Desktop\temp.pdf" }); Console.WriteLine(result); }
public void ConvertToPDF(string html, string outputPath, string copies = "1", string zoom = "1", string orientation = "Portrait", string options = "") { PdfConvert.ConvertHtmlToPdf( new PdfDocument { Url = "-", Html = html, HeaderLeft = "", HeaderRight = "", FooterCenter = "", ExtraParams = new Dictionary <string, string> () { { "disable-javascript", "" }, { "disable-smart-shrinking", "" }, { "images", "" }, { "viewport-size", "800x600" }, { "dpi", "72" }, { "encoding", "'utf-8'" }, { "copies", copies }, { "zoom", zoom }, { "orientation", orientation }, { "quiet", " " + options } } }, new PdfConvertEnvironment { TempFolderPath = Path.GetTempPath(), WkHtmlToPdfPath = WKHTMLToPDFPath(), Timeout = 60000 }, new PdfOutput { OutputFilePath = outputPath } ); }
public static PdfFileGeneratedIntegrationEvent ConsumeAsync(PdfDocumentGenerateIntegrationEvent document) { Console.WriteLine("Pdf File Generate Integration Event Received: {0}", document.DisputeGuid); PdfOutput pdfOutput = new PdfOutput() { OutputStream = new MemoryStream() }; PdfConvert.ConvertHtmlToPdf(document, pdfOutput); var bytes = ((MemoryStream)pdfOutput.OutputStream).ToArray(); if (bytes != null) { pdfOutput.OutputStream.Close(); var base64File = Convert.ToBase64String(bytes); var pdfFile = new PdfFileGeneratedIntegrationEvent { CreatedDateTime = document.CreatedDateTime, DisputeGuid = document.DisputeGuid, FileContentBase64 = base64File }; return(pdfFile); } return(null); }
public static string GerarRelatorio(string pasta, string html, string nomeRelatorio) { var caminho = String.Format("C:/Users/gabri/GitHub/SRCONFI.Projeto/SRCONFI.Projeto.Web/SRCONFI.Projeto.Web/PDF/{0}", pasta); if (!Arquivo.VerificarPasta(caminho)) { Arquivo.CriarPasta(caminho); } string arquivo = String.Format("{0}_{1}.pdf", pasta, DateTime.Now.ToString().Trim() .Replace("/", "").Trim() .Replace(":", "").Trim() .Replace(" ", "").Trim()); var caminhoFinal = String.Format("{0}/{1}", caminho, arquivo); PdfConvert.Environment.Debug = true; PdfConvert.ConvertHtmlToPdf(new PdfDocument { Url = "-", Html = html, HeaderLeft = nomeRelatorio, HeaderRight = "Data: [date] Hora: [time]", FooterCenter = "Página [page] de [topage]" }, new PdfOutput { //OutputStream = Arquivo.AbrirArquivo(caminhoFinal) OutputFilePath = caminhoFinal }); return(caminhoFinal); }
public async Task ConvertStringChineseAsync() { await PdfConvert.ConvertHtmlToPdfAsync(new PdfDocument { Url = "-", Html = "<html><h1>測試</h1></html>" }, new PdfOutput { OutputFilePath = "async_inline_cht.pdf" }); }
void Test_Sample5() { context["Sample 5: Static Cover, Header, Footer, and Content"] = () => { beforeEach = () => { PdfConvert.Convert(new PdfConversionSettings { Title = "My Static Content", PageCoverHtml = @"<!DOCTYPE html> <html> <head></head> <body> <div style=""height: 100vh; text-align: center;""><h1>Cover Page</h1></div> </body></html>", PageHeaderHtml = @"<!DOCTYPE html> <html> <head></head> <body> <h5>HEADER</h5> </body></html>", PageFooterHtml = @"<!DOCTYPE html> <html> <head></head> <body> <h5>FOOTER</h5> </body></html>", Content = @"<h1>Lorem ipsum dolor sit amet consectetuer adipiscing elit I SHOULD BE RED BY JAVASCRIPT</h1><script>document.querySelector('h1').style.color = 'rgb(128,0,0)';</script>", OutputPath = @"C:\temp\sample5.pdf" }); }; it["Should have created a PDF document in the Temp folder"] = () => File.Exists(@"C:\temp\sample5.pdf").ShouldBeTrue(); }; }
public static void writehtmlandpdf(Newtonsoft.Json.Linq.JArray a, int number) { int i = 1; string text = File.ReadAllText("ultra_template.html"); foreach (var aa in a) { text = text.Replace("1\\img" + i, number + "\\" + aa["image"].ToString()); text = text.Replace("desc" + i, aa["text"].ToString()); File.WriteAllText("template" + number + ".html", text); i++; } PdfConvert.ConvertHtmlToPdf(new Codaxy.WkHtmlToPdf.PdfDocument { Url = "template" + number + ".html", HeaderLeft = "[title]", HeaderRight = "[date] [time]", FooterCenter = "Page [page] of [topage]" }, new PdfOutput { OutputFilePath = "pdf" + number + ".pdf" }); }
public async Task ConvertUrlAsync() { await PdfConvert.ConvertHtmlToPdfAsync(new PdfDocument { Url = "http://www.codaxy.com" }, new PdfOutput { OutputFilePath = "async_codaxy.pdf" }); }
void Test_Sample3() { context["Sample 3: Use Input and Output Streams"] = () => { beforeEach = () => { PdfConversionSettings config = new PdfConversionSettings { Title = "Streaming my HTML to PDF" }; using (var fileStream = new FileStream(@"C:\temp\sample3.pdf", FileMode.Create)) { var task = new System.Net.Http.HttpClient().GetStreamAsync("http://www.google.com"); task.Wait(); using (var inputStream = task.Result) { PdfConvert.Convert(config, fileStream, inputStream); } } }; it["Should have created a PDF document in the Temp folder"] = () => File.Exists(@"C:\temp\sample3.pdf").ShouldBeTrue(); }; }
void Given_a_sample_conversion_settings_with_streamed_content_and_output() { context["When performing the PDF Conversion of the provided HTML from and to a stream"] = () => { beforeEach = () => { PdfConversionSettings config = new PdfConversionSettings { Title = "Streaming my HTML to PDF" }; using (var fileStream = new FileStream(@"C:\temp\www.google.com.pdf", FileMode.Create)) { var task = new System.Net.Http.HttpClient().GetStreamAsync("http://www.google.com"); task.Wait(); using (var inputStream = task.Result) { PdfConvert.Convert(config, fileStream, inputStream); } } }; it["Should have created a PDF document in the Temp folder"] = () => File.Exists(@"C:\temp\www.google.com.pdf").ShouldBeTrue(); }; }
static void Main(string[] args) { Console.InputEncoding = Encoding.UTF8; PdfConvert.Environment.Debug = true; PdfConvert.ConvertHtmlToPdf(new PdfDocument { Url = "http://www.codaxy.com" }, new PdfOutput { OutputFilePath = "codaxy.pdf" }); PdfConvert.ConvertHtmlToPdf(new PdfDocument { Url = "http://www.codaxy.com", HeaderLeft = "[title]", HeaderRight = "[date] [time]", FooterCenter = "Page [page] of [topage]" }, new PdfOutput { OutputFilePath = "codaxy_hf.pdf" }); PdfConvert.ConvertHtmlToPdf(new PdfDocument { Url = "-", Html = "<html><h1>test</h1></html>" }, new PdfOutput { OutputFilePath = "inline.pdf" }); PdfConvert.ConvertHtmlToPdf(new PdfDocument { Url = "-", Html = "<html><h1>測試</h1></html>" }, new PdfOutput { OutputFilePath = "inline_cht.pdf" }); }
void Test_Sample4() { context["Sample 4: Output Streams and Specify URL for Input and Cover with Table of Contents"] = () => { beforeEach = () => { PdfConversionSettings config = new PdfConversionSettings { Title = "A little bit of Everything", GenerateToc = true, TocHeaderText = "Table of MY Contents", PageCoverUrl = "https://www.google.com/?q=cover%20page", ContentUrl = "https://www.google.com/?q=content%20page", PageHeaderHtml = @" <!DOCTYPE html> <html><body> <div style=""background-color: red; color: white; text-align: center; width: 100vw;"">SECRET SAUCE</div> </body></html>" }; using (var fileStream = new FileStream(@"C:\temp\sample4.pdf", FileMode.Create)) { PdfConvert.Convert(config, fileStream); } }; it["Should have created a PDF document in the Temp folder"] = () => File.Exists(@"C:\temp\sample4.pdf").ShouldBeTrue(); }; }
public async Task <FileContentResult> GeneratePDFAsync() { //nuget install - Shark.PdfConvert ver 1.0.3 //Note: https://github.com/cp79shark/Shark.PdfConvert //install https://wkhtmltopdf.org/downloads.html //https://www.c-sharpcorner.com/article/Asp-Net-mvc-file-upload-and-download/ // and install Microsoft.Net.Http.Headers from nuget package , if the running project is class library like this. PdfConversionSettings config = new PdfConversionSettings { Title = "My Static Content", Size = PdfPageSize.A4, Content = @"<h3>PDf generated from dot net core!!!</h3> <script>document.querySelector('h1').style.color = 'rgb(128,0,0)';</script>" // OutputPath = @"C:\GeneratedPDF\test.pdf" }; var memoryStream = new MemoryStream(); await Task.Run(() => PdfConvert.Convert(config, memoryStream)); var fileName = "myfileName.pdf"; var mimeType = "application/pdf"; return(new FileContentResult(memoryStream.ToArray(), mimeType) { FileDownloadName = fileName }); }
public Resultado Post(string urlDestino) { string directorio = $"D:\\PdfGen\\{DateTime.Now:yyyy-MM-dd}"; string key = $"{Guid.NewGuid()}"; try { // Validamosdirectorio if (!Directory.Exists(directorio)) { Directory.CreateDirectory(directorio); } // Convertimos PdfConvert.ConvertHtmlToPdf(new PdfDocument { Url = urlDestino }, new PdfOutput { OutputFilePath = $"{directorio}\\{key}.pdf" }); // Pasamso a base64 byte[] bytes = File.ReadAllBytes($"{directorio}\\{key}.pdf"); return(Resultado.Si(Convert.ToBase64String(bytes))); } catch (Exception ex) { return(Resultado.No($"Ah ocurrido un error; {ex.Message}")); } }
public async Task <string> ConvertToPdfAsync(string content) { return(await Task.Run(() => { var headerUrl = $@"{_hostingEnvironment.ContentRootPath}\Reports\Default\header.html"; var footerUrl = $@"{_hostingEnvironment.ContentRootPath}\Reports\Default\footer.html"; var config = new PdfConversionSettings { Title = "Workflow auto-generated report", Content = content, PageHeaderUrl = headerUrl, PageFooterUrl = footerUrl, Margins = new PdfPageMargins { Left = 10, Top = 17 + 20, Right = 10, Bottom = 20 }, OutputPath = $@"{_hostingEnvironment.ContentRootPath}\Reports\AutoGeneratedReport\{Guid.NewGuid()}.pdf", CustomWkHtmlHeaderArgs = "--header-spacing 10", CustomWkHtmlFooterArgs = "--footer-spacing 10", PdfToolPath = $@"{_hostingEnvironment.ContentRootPath}\Utilities\wkhtmltopdf.exe" }; PdfConvert.Convert(config); return config.OutputPath; })); }
public async Task <HttpResponseMessage> GetReport(int id) { Company company = db.Companies.Find(id); if (company == null) { return(Request.CreateResponse(HttpStatusCode.NotFound)); } var plotController = new PlotController(); plotController.ControllerContext = ControllerContext; /* * var store = new UserStore<ApplicationUser>(db); * var manager = new ApplicationUserManager(store); * manager.Find("", ""); * var user = db.Users.Where(u => u.UserName == "*****@*****.**").ToList().SingleOrDefault(); * var identity = manager.ClaimsIdentityFactory.CreateAsync(manager, user, "").Result; * var principal = new ClaimsPrincipal(identity); * HttpContext.Current.User = principal; */ var chart = plotController.GetCompanyStatisticsForMmail(id, 960, 450); var chartStream = await chart.Content.ReadAsStreamAsync(); var chartImage = Bitmap.FromStream(chartStream); var chartLocation = System.AppContext.BaseDirectory + "Areas\\Document\\Views\\Default\\Chart.jpg"; chartImage.Save(chartLocation, ImageFormat.Jpeg); var baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority); var relativeUrl = Url.Route("Document_default", new { id, controller = "Default", action = "EmployeeReport" }); var ms = new MemoryStream(); PdfConvert.ConvertHtmlToPdf(new PdfDocument { Url = new Uri(new Uri(baseUrl), relativeUrl).ToString() }, new PdfOutput { OutputStream = ms }); ms.Position = 0; var response = Request.CreateResponse(); response.Content = new StreamContent(ms); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Document.pdf" }; response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); return(response); }
public void ConvertStringChinese() { PdfConvert.ConvertHtmlToPdf(new PdfDocument { Url = "-", Html = "<html><h1>測試</h1></html>" }, new PdfOutput { OutputFilePath = "inline_cht.pdf" }); }
public void ConvertUrl() { PdfConvert.ConvertHtmlToPdf(new PdfDocument { Url = "http://www.codaxy.com" }, new PdfOutput { OutputFilePath = "codaxy.pdf" }); }
public static void Demo() { PdfConvert.ConvertHtmlToPdf(new PdfDocument { Url = @"layout.html" }, new PdfOutput { OutputFilePath = "layout.pdf" }); }
public IActionResult GenerateProposal() { try { string QRFID = Request.Query["QRFId"]; string urlInitial = HttpContext.Request.Scheme + "://" + HttpContext.Request.Host.Value; string PageURL = urlInitial + "/ProposalDocument/ProposalDocument?QRFId=" + QRFID; string HeaderURL = urlInitial + "/ProposalDocument/_ProposalDocumentHeader?QRFId=" + QRFID; string FooterUrl = urlInitial + "/ProposalDocument/_ProposalDocumentFooter?QRFId=" + QRFID; if (!string.IsNullOrEmpty(QRFID)) { NewQuoteViewModel modelQuote = new NewQuoteViewModel { QRFID = QRFID }; COCommonLibrary.GetCOTourInfoHeader(ref modelQuote, token); string filename = FormatFileName(modelQuote.COHeaderViewModel.TourName) + ".pdf"; string PDFPath = _configuration.GetValue <string>("SystemSettings:ProposalDocumentFilePath"); string FullPDFPath = Path.Combine(PDFPath, filename); if (!Directory.Exists(PDFPath)) { Directory.CreateDirectory(PDFPath); } PdfConvert._configuration = _configuration; PdfConvert.GenerateDocument(PageURL, HeaderURL, FooterUrl, FullPDFPath, token, HttpContext.Request.Cookies); if (filename == null) { return(Content("filename not present")); } #region Update ValidForAcceptance field in mQuote and mQRFPrice collection ResponseStatus objResponseStatus = COCommonLibrary.UpdateValidForAcceptance(_configuration, token, QRFID, ckUserEmailId); #endregion var memory = new MemoryStream(); using (var stream = new FileStream(FullPDFPath, FileMode.Open)) { stream.CopyTo(memory); } memory.Position = 0; return(File(memory, PdfConvert.GetContentType(FullPDFPath), Path.GetFileName(FullPDFPath))); } else { return(null); } } catch (Exception ex) { throw; return(null); } }
private void ExportFileToPDF(string htmlUrl, string exportDirectory, string fileName) { exportDirectory = exportDirectory + "\\"; PdfConvert.ConvertHtmlToPdf(new PdfDocument { Url = htmlUrl }, new PdfOutput { OutputFilePath = exportDirectory + fileName + ".pdf", }); }
public async Task ConvertUrlHeaderFooterAsync() { await PdfConvert.ConvertHtmlToPdfAsync(new PdfDocument { Url = "http://www.codaxy.com", HeaderLeft = "[title]", HeaderRight = "[date] [time]", FooterCenter = "Page [page] of [topage]" }, new PdfOutput { OutputFilePath = "async_codaxy_hf.pdf" }); }
public void ConvertUrlHeaderFooter() { PdfConvert.ConvertHtmlToPdf(new PdfDocument { Url = "http://www.codaxy.com", HeaderLeft = "[title]", HeaderRight = "[date] [time]", FooterCenter = "Page [page] of [topage]" }, new PdfOutput { OutputFilePath = "codaxy_hf.pdf" }); }
public static void ToPdf(string source, string destination) { PdfConvert.Environment.WkHtmlToPdfPath = HostingEnvironment.MapPath("~/plugins/wkhtmltopdf/wkhtmltopdf.exe"); PdfConvert.Environment.Timeout = 30000; PdfConvert.ConvertHtmlToPdf(new PdfDocument { Url = PageUtility.ResolveAbsoluteUrl(source) }, new PdfOutput { OutputFilePath = destination }); }
public ReporterPDF(ReportData inputData, ref ReportNode rnRoot , string templatePath, string outputFilePath) { // absolute output file path string absOutputFilePath = string.Empty; if (Path.IsPathRooted(outputFilePath)) { absOutputFilePath = outputFilePath; } else { absOutputFilePath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), outputFilePath)); } // absolute template path string absTemplatePath = string.Empty; if (Path.IsPathRooted(templatePath)) { absTemplatePath = templatePath; } else { absTemplatePath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), templatePath)); } // does output directory exists string outDir = Path.GetDirectoryName(absOutputFilePath); if (!Directory.Exists(outDir)) { try { Directory.CreateDirectory(outDir); } catch (UnauthorizedAccessException /*ex*/) { throw new UnauthorizedAccessException(string.Format("User not allowed to write under {0}", Directory.GetParent(outDir).FullName)); } catch (Exception ex) { throw new Exception(string.Format("Directory {0} does not exist, and could not be created.", outDir), ex); } } // html file path string htmlFilePath = Path.ChangeExtension(absOutputFilePath, "html"); BuildAnalysisReport(inputData, ref rnRoot, absTemplatePath, htmlFilePath); PdfConvert.ConvertHtmlToPdf(new PdfDocument() { Url = htmlFilePath }, new PdfOutput() { OutputFilePath = absOutputFilePath }); }
static void Main(string[] args) { Console.InputEncoding = Encoding.UTF8; PdfConvert.ConvertHtmlToPdf(new PdfDocument { Pages = { new PdfPage { Html = "http://www.codaxy.com" } } }, new PdfOutput { OutputFilePath = "codaxy.pdf" }); PdfConvert.ConvertHtmlToPdf(new PdfDocument { Pages = { new PdfPage { Html = "http://www.codaxy.com", Header ={ Left = "[title]", Right = "[date] [time]" }, Footer ={ Center = "Page [page] of [topage]" } } } }, new PdfOutput { OutputFilePath = "codaxy_hf.pdf" }); PdfConvert.ConvertHtmlToPdf(new PdfDocument { Pages = { new PdfPage { Html = "<html><h1>test</h1></html>" } } }, new PdfOutput { OutputFilePath = "inline.pdf" }); PdfConvert.ConvertHtmlToPdf(new PdfDocument { Pages = { new PdfPage { Html = "<html><h1>測試</h1></html>" } } }, new PdfOutput { OutputFilePath = "inline_cht.pdf" }); //PdfConvert.ConvertHtmlToPdf("http://tweakers.net", "tweakers.pdf"); }
static void Main(string[] args) { Console.InputEncoding = Encoding.UTF8; PdfConvert.Environment.Debug = false; PdfConvert.ConvertHtmlToPdf(new PdfDocument { Url = "http://www.codaxy.com" }, new PdfOutput { OutputFilePath = "codaxy.pdf" }); PdfConvert.ConvertHtmlToPdf(new PdfDocument { Url = "http://www.codaxy.com", HeaderLeft = "[title]", HeaderRight = "[date] [time]", FooterCenter = "Page [page] of [topage]", FooterFontSize = "10", HeaderFontSize = "20", HeaderFontName = "Comic Sans MS", FooterFontName = "Helvetica" }, new PdfOutput { OutputFilePath = "codaxy_hf.pdf" }); PdfConvert.ConvertHtmlToPdf( new PdfDocument { Html = "<html><h1>test</h1></html>" }, new PdfOutput { OutputFilePath = "inline.pdf" } ); PdfConvert.ConvertHtmlToPdf( new PdfDocument { Html = "<html><h1>測試</h1></html>" }, new PdfOutput { OutputFilePath = "inline_cht.pdf" } ); //PdfConvert.ConvertHtmlToPdf("http://tweakers.net", "tweakers.pdf"); }
void Given_a_sample_conversion_settings_with_http_based_content() { context["When performing the PDF Conversion of the provided HTML from http://www.lipsum.com"] = () => { beforeEach = () => { PdfConvert.Convert(new PdfConversionSettings { Title = "My Static Content from URL", ContentUrl = "http://www.lipsum.com/", OutputPath = @"C:\temp\temp-url.pdf" }); }; it["Should have created a PDF document in the Temp folder"] = () => File.Exists(@"C:\temp\temp-url.pdf").ShouldBeTrue(); }; }
public MemoryStream PdfStream(string url) { var memory = new MemoryStream(); var document = new PdfDocument() { Url = url }; var output = new PdfOutput() { OutputStream = memory }; PdfConvert.ConvertHtmlToPdf(document, output); memory.Position = 0; return(memory); }