public void EncryptedHtml() { //ExStart //ExFor:HtmlLoadOptions.#ctor(String) //ExSummary:Shows how to encrypt an Html document and then open it using a password. // Create and sign an encrypted html document from an encrypted .docx CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw"); SignOptions signOptions = new SignOptions { Comments = "Comment", SignTime = DateTime.Now, DecryptionPassword = "******" }; string inputFileName = MyDir + "Encrypted.docx"; string outputFileName = ArtifactsDir + "HtmlLoadOptions.EncryptedHtml.html"; DigitalSignatureUtil.Sign(inputFileName, outputFileName, certificateHolder, signOptions); // This .html document will need a password to be decrypted, opened and have its contents accessed // The password is specified by HtmlLoadOptions.Password HtmlLoadOptions loadOptions = new HtmlLoadOptions("docPassword"); Assert.AreEqual(signOptions.DecryptionPassword, loadOptions.Password); Document doc = new Document(outputFileName, loadOptions); Assert.AreEqual("Test encrypted document.", doc.GetText().Trim()); //ExEnd }
private void PrintExecute() { try { //CODE AFTER CREATING HTML FILE: //convert html to pdf HtmlLoadOptions htmloptions = new HtmlLoadOptions(@"..\..\Stock.html"); // enter realative file directory adres Document doc = new Document(@"..\..\Stock.html", htmloptions); // enter realative file adres doc.Save("output1.pdf", Aspose.Pdf.SaveFormat.Pdf); //print pdf file var pd = new PrintDialog(); pd.ShowDialog(); var info = new ProcessStartInfo() { Verb = "print", CreateNoWindow = true, FileName = @"", //add file adress WindowStyle = ProcessWindowStyle.Hidden }; Process.Start(info); PrintDialog printDialog = new PrintDialog(); if (printDialog.ShowDialog() == true) { printDialog.PrintVisual(e.grid, "Print"); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
public FileResult Index(string editor1, string codeText, string barcodeType) { // generate a barcode string barcodeImagePath = Path.Combine("wwwroot/barcodes/", Guid.NewGuid() + ".png"); SymbologyEncodeType type = GetBarcodeSymbology(barcodeType); BarcodeGenerator generator = new BarcodeGenerator(type, codeText); generator.Parameters.BackColor = System.Drawing.Color.Transparent; // set resolution of the barcode image generator.Parameters.Resolution = 200; // generate barcode generator.Save(barcodeImagePath, BarCodeImageFormat.Png); // create a unique file name for PDF string fileName = Guid.NewGuid() + ".pdf"; // convert HTML text to stream byte[] byteArray = Encoding.UTF8.GetBytes(editor1); // generate PDF from the HTML MemoryStream stream = new MemoryStream(byteArray); HtmlLoadOptions options = new HtmlLoadOptions(); Document pdfDocument = new Document(stream, options); // add barcode image to the generated PDF pdfDocument = InsertImage(pdfDocument, barcodeImagePath); // create memory stream for the PDF file Stream outputStream = new MemoryStream(); // save PDF to output stream pdfDocument.Save(outputStream); // return generated PDF file return(File(outputStream, System.Net.Mime.MediaTypeNames.Application.Pdf, fileName)); }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Sample HTML. string sampleHtml = "<html><body><table><tr><td>This is sample text.</td><td>Some text.</td></tr><tr><td>This is another sample text.</td><td>Some text.</td></tr></table></body></html>"; //Load html string into memory stream. MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(sampleHtml)); //Load memory stream into workbook. Workbook wb = new Workbook(ms); //Save the workbook in xlsx format. wb.Save(dataDir + "outputWithout_AutoFitColsAndRows.xlsx"); //Specify the HTMLLoadOptions and set AutoFitColsAndRows = true. HtmlLoadOptions opts = new HtmlLoadOptions(); opts.AutoFitColsAndRows = true; //Load memory stream into workbook with the above HTMLLoadOptions. wb = new Workbook(ms, opts); //Save the workbook in xlsx format. wb.Save(dataDir + "outputWith_AutoFitColsAndRows.xlsx"); // ExEnd:1 }
public static void Run() { // ExStart:LoadMessageWithLoadOptions // The path to the File directory. string dataDir = RunExamples.GetDataDir_Email(); // Load Eml, html, mhtml, msg and dat file MailMessage mailMessage = MailMessage.Load(dataDir + "Message.eml", new EmlLoadOptions()); MailMessage.Load(dataDir + "description.html", new HtmlLoadOptions()); MailMessage.Load(dataDir + "Message.mhtml", new MhtmlLoadOptions()); MailMessage.Load(dataDir + "Message.msg", new MsgLoadOptions()); // loading with custom options EmlLoadOptions emlLoadOptions = new EmlLoadOptions { PrefferedTextEncoding = Encoding.UTF8, PreserveTnefAttachments = true }; MailMessage.Load(dataDir + "description.html", emlLoadOptions); HtmlLoadOptions htmlLoadOptions = new HtmlLoadOptions { PrefferedTextEncoding = Encoding.UTF8, ShouldAddPlainTextView = true, PathToResources = dataDir }; MailMessage.Load(dataDir + "description.html", emlLoadOptions); // ExEnd:LoadMessageWithLoadOptions }
public void EncryptedHtml() { //ExStart //ExFor:HtmlLoadOptions.#ctor(String) //ExSummary:Shows how to encrypt an Html document, and then open it using a password. // Create and sign an encrypted HTML document from an encrypted .docx. CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw"); SignOptions signOptions = new SignOptions { Comments = "Comment", SignTime = DateTime.Now, DecryptionPassword = "******" }; string inputFileName = MyDir + "Encrypted.docx"; string outputFileName = ArtifactsDir + "HtmlLoadOptions.EncryptedHtml.html"; DigitalSignatureUtil.Sign(inputFileName, outputFileName, certificateHolder, signOptions); // To load and read this document, we will need to pass its decryption // password using a HtmlLoadOptions object. HtmlLoadOptions loadOptions = new HtmlLoadOptions("docPassword"); Assert.AreEqual(signOptions.DecryptionPassword, loadOptions.Password); Document doc = new Document(outputFileName, loadOptions); Assert.AreEqual("Test encrypted document.", doc.GetText().Trim()); //ExEnd }
public void BaseUri() { //ExStart //ExFor:HtmlLoadOptions.#ctor(LoadFormat,String,String) //ExFor:LoadOptions.LoadFormat //ExFor:LoadFormat //ExSummary:Shows how to specify a base URI when opening an html document. // If we want to load an .html document which contains an image linked by a relative URI // while the image is in a different location, we will need to resolve the relative URI into an absolute one // by creating an HtmlLoadOptions and providing a base URI HtmlLoadOptions loadOptions = new HtmlLoadOptions(LoadFormat.Html, "", ImageDir); Assert.AreEqual(LoadFormat.Html, loadOptions.LoadFormat); Document doc = new Document(MyDir + "Missing image.html", loadOptions); // While the image was broken in the input .html, it was successfully found in our base URI Shape imageShape = (Shape)doc.GetChildNodes(NodeType.Shape, true)[0]; Assert.True(imageShape.IsImage); // The image will be displayed correctly by the output document doc.Save(ArtifactsDir + "HtmlLoadOptions.BaseUri.docx"); //ExEnd }
public void BaseUri() { //ExStart //ExFor:HtmlLoadOptions.#ctor(LoadFormat,String,String) //ExFor:LoadOptions.#ctor(LoadFormat, String, String) //ExFor:LoadOptions.LoadFormat //ExFor:LoadFormat //ExSummary:Shows how to specify a base URI when opening an html document. // Suppose we want to load an .html document that contains an image linked by a relative URI // while the image is in a different location. In that case, we will need to resolve the relative URI into an absolute one. // We can provide a base URI using an HtmlLoadOptions object. HtmlLoadOptions loadOptions = new HtmlLoadOptions(LoadFormat.Html, "", ImageDir); Assert.AreEqual(LoadFormat.Html, loadOptions.LoadFormat); Document doc = new Document(MyDir + "Missing image.html", loadOptions); // While the image was broken in the input .html, our custom base URI helped us repair the link. Shape imageShape = (Shape)doc.GetChildNodes(NodeType.Shape, true)[0]; Assert.True(imageShape.IsImage); // This output document will display the image that was missing. doc.Save(ArtifactsDir + "HtmlLoadOptions.BaseUri.docx"); //ExEnd doc = new Document(ArtifactsDir + "HtmlLoadOptions.BaseUri.docx"); Assert.True(((Shape)doc.GetChild(NodeType.Shape, 0, true)).ImageData.ImageBytes.Length > 0); }
public void IgnoreNoscriptElements(bool ignoreNoscriptElements) { //ExStart //ExFor:HtmlLoadOptions.IgnoreNoscriptElements //ExSummary:Shows how to ignore <noscript> HTML elements. const string html = @" <html> <head> <title>NOSCRIPT</title> <meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8""> <script type=""text/javascript""> alert(""Hello, world!""); </script> </head> <body> <noscript><p>Your browser does not support JavaScript!</p></noscript> </body> </html>"; HtmlLoadOptions htmlLoadOptions = new HtmlLoadOptions(); htmlLoadOptions.IgnoreNoscriptElements = ignoreNoscriptElements; Document doc = new Document(new MemoryStream(Encoding.UTF8.GetBytes(html)), htmlLoadOptions); doc.Save(ArtifactsDir + "HtmlLoadOptions.IgnoreNoscriptElements.pdf"); //ExEnd Aspose.Pdf.Document pdfDoc = new Aspose.Pdf.Document(ArtifactsDir + "HtmlLoadOptions.IgnoreNoscriptElements.pdf"); TextAbsorber textAbsorber = new TextAbsorber(); textAbsorber.Visit(pdfDoc); Assert.AreEqual(ignoreNoscriptElements ? "" : "Your browser does not support JavaScript!", textAbsorber.Text); }
public void SupportVml(bool doSupportVml) { //ExStart //ExFor:HtmlLoadOptions.#ctor //ExFor:HtmlLoadOptions.SupportVml //ExSummary:Shows how to support VML while parsing a document. HtmlLoadOptions loadOptions = new HtmlLoadOptions(); // If value is true, then we take VML code into account while parsing the loaded document loadOptions.SupportVml = doSupportVml; // This document contains an image within "<!--[if gte vml 1]>" tags, and another different image within "<![if !vml]>" tags // Upon loading the document, only the contents of the first tag will be shown if VML is enabled, // and only the contents of the second tag will be shown otherwise Document doc = new Document(MyDir + "VML conditional.htm", loadOptions); // Only one of the two unique images will be loaded, depending on the value of loadOptions.SupportVml Shape imageShape = (Shape)doc.GetChild(NodeType.Shape, 0, true); if (doSupportVml) { TestUtil.VerifyImageInShape(400, 400, ImageType.Jpeg, imageShape); } else { TestUtil.VerifyImageInShape(400, 400, ImageType.Png, imageShape); } //ExEnd }
public void GetSelectAsSdt() { //ExStart //ExFor:HtmlLoadOptions.PreferredControlType //ExSummary:Shows how to set preffered type of document nodes that will represent imported <input> and <select> elements. const string html = @" <html> <select name='ComboBox' size='1'> <option value='val1'>item1</option> <option value='val2'></option> </select> </html> "; HtmlLoadOptions htmlLoadOptions = new HtmlLoadOptions(); htmlLoadOptions.PreferredControlType = HtmlControlType.StructuredDocumentTag; Document doc = new Document(new MemoryStream(Encoding.UTF8.GetBytes(html)), htmlLoadOptions); NodeCollection nodes = doc.GetChildNodes(NodeType.StructuredDocumentTag, true); StructuredDocumentTag tag = (StructuredDocumentTag)nodes[0]; //ExEnd Assert.AreEqual(2, tag.ListItems.Count); Assert.AreEqual("val1", tag.ListItems[0].Value); Assert.AreEqual("val2", tag.ListItems[1].Value); }
static void Example2() { var html = @" <html> <style> @page { size: A5 landscape; margin: 6cm 1cm 1cm; mso-header-margin: 1cm; mso-footer-margin: 1cm; } body { background: #EDEDED; border: 1pt solid black; padding: 20pt; } br { page-break-before: always; } p { margin: 0; } header { color: #FF0000; text-align: center; } main { color: #00B050; } footer { color: #0070C0; text-align: right; } </style> <body> <header> <p>Header text.</p> </header> <main> <p>First page.</p> <br> <p>Second page.</p> <br> <p>Third page.</p> <br> <p>Fourth page.</p> </main> <footer> <p>Footer text.</p> <p>Page <span style='mso-field-code:PAGE'>1</span> of <span style='mso-field-code:NUMPAGES'>1</span></p> </footer> </body> </html>"; var htmlLoadOptions = new HtmlLoadOptions(); using (var htmlStream = new MemoryStream(htmlLoadOptions.Encoding.GetBytes(html))) { // Load input HTML text as stream. var document = DocumentModel.Load(htmlStream, htmlLoadOptions); // Save output PDF file. document.Save("Output2.pdf"); } }
public void ConvertHTMLtoPDF() { HtmlLoadOptions options = new HtmlLoadOptions(); var docFileName = System.IO.Path.Combine(_dataDir, "exames.html"); Document pdfDocument = new Document(docFileName, options); var newDocFileName = System.IO.Path.Combine(_dataDir, "Exame.pdf"); pdfDocument.Save(newDocFileName); }
public static void Main() { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); // Specify the The base path/url for the html file which serves as images database String basePath = "C:/temp/"; HtmlLoadOptions htmloptions = new HtmlLoadOptions(basePath); // Load HTML file Document doc = new Document(dataDir+ "Input.html", htmloptions); // Save HTML file doc.Save(dataDir+ "output.pdf"); }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion(); // Specify the The base path/url for the html file which serves as images database String basePath = "C:/temp/"; HtmlLoadOptions htmloptions = new HtmlLoadOptions(basePath); // Load HTML file Document doc = new Document(dataDir+ "Input.html", htmloptions); // Save HTML file doc.Save(dataDir+ "HTMLToPDF_out.pdf"); }
///<Summary> /// UpdateContents method to update contents ///</Summary> public Response UpdateContents(string fileName, string htmldata, string outputType) { Opts.AppName = "Editor"; Opts.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; outputType = outputType.ToLower(); var foldername = Guid.NewGuid().ToString(); var fn = Path.GetFileNameWithoutExtension(fileName) + outputType; var resultfile = Config.Configuration.OutputDirectory + foldername + "/" + fn; Directory.CreateDirectory(Path.GetDirectoryName(resultfile)); try { switch (outputType) { case ".html": File.WriteAllText(resultfile, htmldata); break; default: var lo = new HtmlLoadOptions() { LoadFormat = LoadFormat.Html, Encoding = Encoding.UTF8 }; Document doc; using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(htmldata))) doc = new Document(stream, lo); doc.Save(resultfile); break; } return(new Response() { FileName = HttpUtility.UrlEncode(fn), FolderName = foldername, StatusCode = 200 }); } catch (Exception ex) { Console.WriteLine(ex.Message); return(new Response() { FileName = HttpUtility.UrlEncode(fn), FolderName = foldername, StatusCode = 500, Status = ex.Message }); } }
public static void Main() { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); // Specify the The base path/url for the html file which serves as images database String basePath = "C:/temp/"; HtmlLoadOptions htmloptions = new HtmlLoadOptions(basePath); // Load HTML file Document doc = new Document(dataDir + "Input.html", htmloptions); // Save HTML file doc.Save(dataDir + "output.pdf"); }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion(); // Specify the The base path/url for the html file which serves as images database String basePath = "C:/temp/"; HtmlLoadOptions htmloptions = new HtmlLoadOptions(basePath); // Load HTML file Document doc = new Document(dataDir + "Input.html", htmloptions); // Save HTML file doc.Save(dataDir + "HTMLToPDF_out.pdf"); }
public IActionResult Create(CertificateViewModel model) { string Name = model.Name; string _StartDate = "January 1, " + model.Year; string _EndDate = "December 31, " + model.Year; ComponentInfo.SetLicense("FREE-LIMITED-KEY"); var htmlLoadOptions = new HtmlLoadOptions(); // Build Doc from Scratch var document = new DocumentModel(); Section section = new Section(document); document.Sections.Add(section); document.Content.Start .LoadText("<div style='text-align: center;margin-top: 30px;'><img src='https://rdat20200218122513.azurewebsites.net/theme/dist/img/title_one.png' alt='Certificate Top' /></div>", new HtmlLoadOptions()) .LoadText("<div style='text-align: center;font-size: 28px;font-weight: bold;padding: 20px;'>" + model.Name + "</div>", new HtmlLoadOptions()) .LoadText("<div style='text-align: center;padding: 10px;'>In accordance with Federal Motor Carrier Safety Regulations, Part 382, the above-named company is a member and full participant in a managed drug and alcohol testing program operated by:.</div>", new HtmlLoadOptions()) .LoadText("<div style='text-align: center;padding: 10px;'><img src='https://rdat20200218122513.azurewebsites.net/theme/dist/img/mid_one.png' alt='Certificate Top' /></div>", new HtmlLoadOptions()) .LoadText("<div style='text-align: center;padding: 10px;'>Trucking Qualifications Services, LLC confirms to the rules set forth in 49 CFR, Part 40, Procedures for the Drug and Alcohol Testing Industry Association and all staff members are certified per the requirements of the federal regulations contained in the Code of Federal Register Part 40.33.</div>", new HtmlLoadOptions()) .LoadText("<div style='text-align: center;padding: 10px;'>All random selections percentage of at least 50% drug and at least 10% alcohol is being maintained in accordance with these regulations.</div>", new HtmlLoadOptions()) .LoadText("<table style='width: 100%;' cellpadding='5' cellspacing='5'><tr><td><strong>Trucking Qualifications Services LLC</strong><br>6250 Shiloh Road, Ste. 230<br>Alpharetta, Georgia 30005</td><td style='text-align: right;'>Program Start Date: " + _StartDate + "<br>Program End Date: " + _EndDate + "</td></tr></table>", new HtmlLoadOptions()) .LoadText("<div style='text-align: center;padding-right: 30px;'><img src='https://rdat20200218122513.azurewebsites.net/theme/dist/img/slice_bottom.png' alt='Certificate Bottom' /></div>", new HtmlLoadOptions()); var pageSetup1 = document.Sections[0].PageSetup; // Set page orientation. pageSetup1.Orientation = Orientation.Landscape; // Set page margins. pageSetup1.PageMargins.Top = 10; pageSetup1.PageMargins.Bottom = 0; // Set paper type. pageSetup1.PaperType = PaperType.Letter; document.Save(@"wwwroot/Output.pdf"); return(File(@"Output.pdf", "application/pdf", "certificate.pdf")); }
public ActionResult Pdf(string view, LaporanViewModel vm, string masterPage = "~/Views/PrintReport/_MasterPage.cshtml", Func <string, string> htmlProcessing = null, bool isLandscape = false, int tryCount = 0) { var license = new License(); license.SetLicense(ConfigurationManager.BaseDirectory + @"\lib\Aspose.Pdf.lic"); license.Embedded = true; var html = RenderViewToString(this, view, vm, masterPage); if (htmlProcessing != null) { html = htmlProcessing(html); } using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(html))) { try { var page = new PageInfo { Height = isLandscape ? PageSize.A4Width : PageSize.A4Height, Width = isLandscape ? PageSize.A4Height : PageSize.A4Width, IsLandscape = isLandscape, Margin = new MarginInfo(8, 10, 8, 10), }; var options = new HtmlLoadOptions(ConfigurationManager.BaseUrl) { PageInfo = page }; var pdf = new Document(stream, options) { PageInfo = page }; var os = new MemoryStream(); pdf.Save(os, SaveFormat.Pdf); os.Position = 0; return(File(os, MimeMapping.GetMimeMapping(".pdf"), $"{vm.Ujian.NamaUjian}-{vm.Sesi.MyKad}.pdf")); } catch (NotSupportedException e) when(e.Message.Contains("woff") && tryCount < 3) { return(Pdf(view, vm, masterPage, htmlProcessing, isLandscape, tryCount + 1)); } catch (NotSupportedException e) when(e.Message.Contains("woff") && tryCount >= 3) { return(Content(html)); } } }
[Test] //ExSkip public void WebRequestTimeout() { // Create a new HtmlLoadOptions object and verify its timeout threshold for a web request. HtmlLoadOptions options = new HtmlLoadOptions(); // When loading an Html document with resources externally linked by a web address URL, // Aspose.Words will abort web requests that fail to fetch the resources within this time limit, in milliseconds. Assert.AreEqual(100000, options.WebRequestTimeout); // Set a WarningCallback that will record all warnings that occur during loading. ListDocumentWarnings warningCallback = new ListDocumentWarnings(); options.WarningCallback = warningCallback; // Load such a document and verify that a shape with image data has been created. // This linked image will require a web request to load, which will have to complete within our time limit. string html = $@" <html> <img src=""{AsposeLogoUrl}"" alt=""Aspose logo"" style=""width:400px;height:400px;""> </html> "; Document doc = new Document(new MemoryStream(Encoding.UTF8.GetBytes(html)), options); Shape imageShape = (Shape)doc.GetChild(NodeType.Shape, 0, true); Assert.AreEqual(7498, imageShape.ImageData.ImageBytes.Length); Assert.AreEqual(0, warningCallback.Warnings().Count); // Set an unreasonable timeout limit and try load the document again. options.WebRequestTimeout = 0; doc = new Document(new MemoryStream(Encoding.UTF8.GetBytes(html)), options); // A web request that fails to obtain an image within the time limit will still produce an image. // However, the image will be the red 'x' that commonly signifies missing images. imageShape = (Shape)doc.GetChild(NodeType.Shape, 0, true); Assert.AreEqual(924, imageShape.ImageData.ImageBytes.Length); // We can also configure a custom callback to pick up any warnings from timed out web requests. Assert.AreEqual(WarningSource.Html, warningCallback.Warnings()[0].Source); Assert.AreEqual(WarningType.DataLoss, warningCallback.Warnings()[0].WarningType); Assert.AreEqual($"Couldn't load a resource from \'{AsposeLogoUrl}\'.", warningCallback.Warnings()[0].Description); Assert.AreEqual(WarningSource.Html, warningCallback.Warnings()[1].Source); Assert.AreEqual(WarningType.DataLoss, warningCallback.Warnings()[1].WarningType); Assert.AreEqual("Image has been replaced with a placeholder.", warningCallback.Warnings()[1].Description); doc.Save(ArtifactsDir + "HtmlLoadOptions.WebRequestTimeout.docx"); }
[Test] //ExSkip public void WebRequestTimeout() { // Create a new HtmlLoadOptions object and verify its timeout threshold for a web request HtmlLoadOptions options = new HtmlLoadOptions(); // When loading an Html document with resources externally linked by a web address URL, // web requests that fetch these resources that fail to complete within this time limit will be aborted Assert.AreEqual(100000, options.WebRequestTimeout); // Set a WarningCallback that will record all warnings that occur during loading ListDocumentWarnings warningCallback = new ListDocumentWarnings(); options.WarningCallback = warningCallback; // Load such a document and verify that a shape with image data has been created, // provided the request to get that image took place within the timeout limit string html = $@" <html> <img src=""{AsposeLogoUrl}"" alt=""Aspose logo"" style=""width:400px;height:400px;""> </html> "; Document doc = new Document(new MemoryStream(Encoding.UTF8.GetBytes(html)), options); Shape imageShape = (Shape)doc.GetChild(NodeType.Shape, 0, true); Assert.AreEqual(7498, imageShape.ImageData.ImageBytes.Length); Assert.AreEqual(0, warningCallback.Warnings().Count); // Set an unreasonable timeout limit and load the document again options.WebRequestTimeout = 0; doc = new Document(new MemoryStream(Encoding.UTF8.GetBytes(html)), options); // If a request fails to complete within the timeout limit, a shape with image data will still be produced // However, the image will be the red 'x' that commonly signifies missing images imageShape = (Shape)doc.GetChild(NodeType.Shape, 0, true); Assert.AreEqual(924, imageShape.ImageData.ImageBytes.Length); // A timeout like this will also accumulate warnings that can be picked up by a WarningCallback implementation Assert.AreEqual(WarningSource.Html, warningCallback.Warnings()[0].Source); Assert.AreEqual(WarningType.DataLoss, warningCallback.Warnings()[0].WarningType); Assert.AreEqual($"The resource \'{AsposeLogoUrl}\' couldn't be loaded.", warningCallback.Warnings()[0].Description); Assert.AreEqual(WarningSource.Html, warningCallback.Warnings()[1].Source); Assert.AreEqual(WarningType.DataLoss, warningCallback.Warnings()[1].WarningType); Assert.AreEqual("Image has been replaced with a placeholder.", warningCallback.Warnings()[1].Description); doc.Save(ArtifactsDir + "HtmlLoadOptions.WebRequestTimeout.docx"); }
public byte[] ConvertToPDF() { string _template = FormEmailBody(); HtmlLoadOptions options = new HtmlLoadOptions(); byte[] byteArray = Encoding.UTF8.GetBytes(_template); MemoryStream stream = new MemoryStream(byteArray); Document pdfDocument = new Document(stream, options); var outputFile = new MemoryStream(); pdfDocument.Save(outputFile); byte[] _btPDF = outputFile.ToArray(); return(_btPDF); //pdfDocument.Save(dataDir + "\\html_test.PDF",SaveFormat.Pdf); //pdfDocument.Save(); }
// ExEnd:HTMLToPDFHelper public static void RenderContentToSamePage() { // ExStart:RenderContentToSamePage // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion(); // Initialize HTMLLoadSave Options HtmlLoadOptions options = new HtmlLoadOptions(); // Set Render to single page property options.IsRenderToSinglePage = true; // Load document Document doc = new Document(dataDir + "HTMLToPDF.html", options); // Save doc.Save(dataDir + "RenderContentToSamePage.pdf"); // ExEnd:RenderContentToSamePage }
public void SupportVml() { //ExStart //ExFor:HtmlLoadOptions.SupportVml //ExSummary:Shows how to parse HTML document with conditional comments like "<!--[if gte vml 1]>" and "<![if !vml]>" HtmlLoadOptions loadOptions = new HtmlLoadOptions(); //If value is true, then we parse "<!--[if gte vml 1]>", else parse "<![if !vml]>" loadOptions.SupportVml = true; //Wait for a response, when loading external resources loadOptions.WebRequestTimeout = 1000; Document doc = new Document(MyDir + "Shape.VmlAndDml.htm", loadOptions); doc.Save(MyDir + @"\Artifacts\Shape.VmlAndDml.docx"); //ExEnd }
public void SupportVml(bool supportVml) { //ExStart //ExFor:HtmlLoadOptions.SupportVml //ExSummary:Demonstrates how to parse html document with conditional comments like "<!--[if gte vml 1]>" and "<![if !vml]>" HtmlLoadOptions loadOptions = new HtmlLoadOptions(); //If SupportVml = true, then we parse "<!--[if gte vml 1]>", else parse "<![if !vml]>" loadOptions.SupportVml = supportVml; //Wait for a response, when loading external resources loadOptions.WebRequestTimeout = 1000; Document doc = new Document(MyDir + "Shape.VmlAndDml.htm", loadOptions); doc.Save(MyDir + @"\Artifacts\Shape.VmlAndDml.docx"); //ExEnd }
public static MemoryStream CreatePDFFromStream(MemoryStream stream, string optionsUrl) { // Load Options HtmlLoadOptions options = new HtmlLoadOptions(); if (!optionsUrl.Equals(string.Empty)) { options = new HtmlLoadOptions(optionsUrl); } // Load HTML file Document pdfDocument = new Document(stream, options); // Transform it to MemoryStream MemoryStream outputStream = new MemoryStream(); return(outputStream); }
public static void Run() { try { // ExStart:WebPageToPDF // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion(); // Create a request for the URL. WebRequest request = WebRequest.Create("https:// En.wikipedia.org/wiki/Main_Page"); // If required by the server, set the credentials. request.Credentials = CredentialCache.DefaultCredentials; // Time out in miliseconds before the request times out // Request.Timeout = 100; // Get the response. HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Get the stream containing content returned by the server. Stream dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream); // Read the content. string responseFromServer = reader.ReadToEnd(); reader.Close(); dataStream.Close(); response.Close(); MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer)); HtmlLoadOptions options = new HtmlLoadOptions("https:// En.wikipedia.org/wiki/"); // Load HTML file Document pdfDocument = new Document(stream, options); options.PageInfo.IsLandscape = true; // Save output as PDF format pdfDocument.Save(dataDir + "WebPageToPDF_out.pdf"); // ExEnd:WebPageToPDF } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public static void RenderHTMLwithSVGData() { // ExStart:RenderHTMLwithSVGData // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion(); // Set input file path string inFile = dataDir + "HTMLSVG.html"; // Set output file path string outFile = dataDir + "RenderHTMLwithSVGData.pdf"; // Initialize HtmlLoadOptions HtmlLoadOptions options = new HtmlLoadOptions(Path.GetDirectoryName(inFile)); // Initialize Document object Document pdfDocument = new Document(inFile, options); // save pdfDocument.Save(outFile); // ExEnd:RenderHTMLwithSVGData }
public static void Run() { // ExStart:LoadAndSaveHtmlFormFieldasContentControlinDOCX // The path to the documents directory. string dataDir = RunExamples.GetDataDir_LoadingAndSaving(); HtmlLoadOptions lo = new HtmlLoadOptions(); lo.PreferredControlType = HtmlControlType.StructuredDocumentTag; //Load the HTML document Document doc = new Document(dataDir + @"input.html", lo); //Save the HTML document into DOCX doc.Save(dataDir + "output.docx", SaveFormat.Docx); // ExEnd:LoadAndSaveHtmlFormFieldasContentControlinDOCX Console.WriteLine("\nHtml form fields are exported as content control successfully."); }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); string filePath = dataDir + "Book1.html"; // Instantiate LoadOptions specified by the LoadFormat. HtmlLoadOptions loadOptions = new HtmlLoadOptions(LoadFormat.Html); // Create a Workbook object and opening the file from its path Workbook wb = new Workbook(filePath, loadOptions); // Save the MHT file wb.Save(filePath + "output.xlsx"); // ExEnd:1 }
private static void CreatePdfDocument(bool withSubFields) { using (var licenseStream = GetBlobDataFromAzure("legal-agreements", "Aspose.Total.lic")) { var license = new License(); licenseStream.Position = 0; license.SetLicense(licenseStream); } // Create a request for the URL. var httpsLocalhostServiceCreatelegalagreementTrue = withSubFields ? "https://localhost/service/CreateLegalAgreement/true" : "https://localhost/service/CreateLegalAgreement/false"; var request = WebRequest.Create(httpsLocalhostServiceCreatelegalagreementTrue); request.Credentials = CredentialCache.DefaultCredentials; using (var response = (HttpWebResponse)request.GetResponse()) { using (var dataStream = response.GetResponseStream()) { using (var reader = new StreamReader(dataStream)) { var responseFromServer = reader.ReadToEnd(); var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer)); var options = new HtmlLoadOptions(httpsLocalhostServiceCreatelegalagreementTrue); // Load HTML file var pdfDocument = new Document(stream, options); options.PageInfo.IsLandscape = false; pdfDocument.Info.Title = "SFA Agreement"; // Save output as PDF format var legalAgreementSubPdf = withSubFields ? @".\_Agreement_V1_Sub.pdf" : @".\_Agreement_V1.pdf"; pdfDocument.Save(legalAgreementSubPdf); } } } }
public static void Run() { try { // ExStart:HTMLToPDF // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion(); HtmlLoadOptions options = new HtmlLoadOptions(); options.CustomLoaderOfExternalResources = new LoadOptions.ResourceLoadingStrategy(SamePictureLoader); Document pdfDocument = new Document(dataDir + "HTMLToPDF.html", options); pdfDocument.Save("HTMLToPDF_out.pdf"); // ExEnd:HTMLToPDF } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public static void Run() { try { // ExStart:ProvideCredentialsDuringHTMLToPDF // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion(); // Create a request for the URL. WebRequest request = WebRequest.Create("http:// My.signchart.com/Report/PrintBook.asp?ProjectGuid=6FB9DBB0-"); // If required by the server, set the credentials. request.Credentials = CredentialCache.DefaultCredentials; // Get the response. HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Get the stream containing content returned by the server. Stream dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream); // Read the content. string responseFromServer = reader.ReadToEnd(); reader.Close(); dataStream.Close(); response.Close(); MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer)); HtmlLoadOptions options = new HtmlLoadOptions("http:// My.signchart.com/"); options.ExternalResourcesCredentials = CredentialCache.DefaultCredentials; // Load HTML file Document pdfDocument = new Document(stream, options); // Save resultant file pdfDocument.Save("ProvideCredentialsDuringHTMLToPDF_out.pdf"); // ExEnd:ProvideCredentialsDuringHTMLToPDF } catch (Exception ex) { Console.WriteLine(ex.Message); } }
protected void ExportButton_Click(object sender, EventArgs e) { StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); if (ExportDataSource != null) { this.AllowPaging = false; this.DataSource = ExportDataSource; this.DataBind(); } this.RenderBeginTag(hw); this.HeaderRow.RenderControl(hw); foreach (GridViewRow row in this.Rows) { row.RenderControl(hw); } this.FooterRow.RenderControl(hw); this.RenderEndTag(hw); string heading = string.IsNullOrEmpty(ExportFileHeading) ? string.Empty : ExportFileHeading; string pageSource = "<html><head></head><body>" + heading + sw.ToString() + "</body></html>"; // Check for license and apply if exists if (File.Exists(LicenseFilePath)) { License license = new License(); license.SetLicense(LicenseFilePath); } string fileName = System.Guid.NewGuid() + ".pdf"; Aspose.Pdf.Document pdf; HtmlLoadOptions htmlLoadOptions = new HtmlLoadOptions(); MemoryStream outputstream = new MemoryStream(); htmlLoadOptions.InputEncoding = "UTF-8"; if (ExportInLandscape) { htmlLoadOptions.PageInfo.Width = 800; htmlLoadOptions.PageInfo.Height = 600; } using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(pageSource))) { pdf = new Document(stream, htmlLoadOptions); } if (!string.IsNullOrEmpty(ExportOutputPathOnServer) && Directory.Exists(ExportOutputPathOnServer)) { try { pdf.Save(ExportOutputPathOnServer + "\\" + fileName); } catch (Exception) { } } pdf.Save(outputstream); byte[] bytes = outputstream.GetBuffer(); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "application/pdf"; HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + fileName); HttpContext.Current.Response.BinaryWrite(bytes); HttpContext.Current.Response.End(); }