1. Tag Results
html-to-pdf (18)
1 - 18 of 18
How to add custom fonts to headers and footers when converting HTML to PDF in C#
Our Syncfusion HTML-to-PDF converter is a .NET PDF library for converting webpages, SVG MHTML and HTML files to PDF using C#. It uses the popular rendering engine Blink (Google Chrome). It is reliable and accurate. The result preserves all graphics, images, text, fonts, and the layout of the original HTML document or webpage. You have the flexibility to customize fonts in header and footer elements of your generated PDF. This can be achieved by utilizing the PdfTrueTypeFont class from the Syncfusion.Pdf.Graphics namespace. To apply a custom font, you first need to load the desired font from a file and pass it into the PdfTrueTypeFont constructor. The PdfTrueTypeFont constructor accepts parameters like the font file path, font size, and style (e.g., bold, italic). Once the font is initialized, you can assign it to the header or footer elements of the PDF. Steps to adding custom font in footer while performing HTML to PDF conversion Create a new console application project. Install the Syncfusion.HtmlToPdfConverter.Winforms NuGet package as a reference to your console application from Nuget.org. Include the following namespaces in the Program.cs file. C# using System.Drawing; using Syncfusion.HtmlConverter; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; Use the following code sample in Program.cs to add custom font in footer while performing HTML to PDF conversion C# // Initialize the HTML to PDF converter HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(); BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings(); // Create font and brush for the footer element FileStream fontStream = new FileStream(@"calibri.ttf", FileMode.Open, FileAccess.Read); PdfFont font = new PdfTrueTypeFont(fontStream, 10); PdfBrush brush = new PdfSolidBrush(Color.Black); // Create a PDF page template element for the footer with specified bounds PdfPageTemplateElement footer = new PdfPageTemplateElement(new RectangleF(0, 0, blinkConverterSettings.PdfPageSize.Width, 50)); // Create a page number field for the footer PdfPageNumberField pageNumber = new PdfPageNumberField(font, PdfBrushes.Black); // Create a page count field for the footer PdfPageCountField count = new PdfPageCountField(font, PdfBrushes.Black); // Add page number and page count fields to a composite field for formatted display PdfCompositeField compositeField = new PdfCompositeField(font, PdfBrushes.Black, "Page {0} of {1}", pageNumber, count); // Draw the composite field in the footer compositeField.Draw(footer.Graphics, PointF.Empty); // Assign the footer element to the PDF footer settings of the Blink converter blinkConverterSettings.PdfFooter = footer; // Set the Blink viewport size blinkConverterSettings.ViewPortSize = new Size(1024, 0); // Assign the Blink converter settings to the HTML converter htmlConverter.ConverterSettings = blinkConverterSettings; // Convert the specified URL to PDF PdfDocument document = htmlConverter.Convert("https://www.google.com/"); // Create a file stream to save the generated PDF using(FileStream fileStream = new FileStream("Output.pdf", FileMode.Create, FileAccess.ReadWrite)) { // Save the PDF document to the file stream document.Save(fileStream); } // Close the document document.Close(true); A complete working sample can be downloaded from HTML-to-PDF-Framework-Footer-Custom-Font By executing the program, a PDF file will be generated with the footer text displayed in the Calibri font, as shown below. Take a moment to peruse the documentation, where you can find converting HTML to PDF document with Header and Footer.
How to Add RTL Languages When Converting HTML to PDF in .NET Core?
Our Syncfusion® HTML-to-PDF converter is a .NET PDF library for converting webpages, SVG MHTML and HTML files to PDF using C#. It uses the popular rendering engine Blink (Google Chrome). It is reliable and accurate. The result preserves all graphics, images, text, fonts, and the layout of the original HTML document or webpage. Using this library, you can add the Arabic text in the TOC of the PDF when performing HTML to PDF conversion. We used arial-unicode-ms font that supports Arabic text, you can specify such font under PdfTrueTypeFont class and assign it to HtmlToPdfTocStyle. However, if you want to use a different font that supports Arabic text then you can replace it. Steps to adding multi-language support, including Arabic, for TOC in HTML to PDF conversion Create a new console application project. Install the Syncfusion.HtmlToPdfConverter.Net.Windows NuGet package as a reference to your console application from Nuget.org. Include the following namespaces in the Program.cs file. C# using Syncfusion.Drawing; using Syncfusion.HtmlConverter; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.HtmlToPdf; Use the following code sample in Program.cs to add multi-language support, including Arabic, for TOC in HTML to PDF conversion C# //Initialize the HTML to PDF converter. HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(); //Initialize blink converter settings. BlinkConverterSettings settings = new BlinkConverterSettings(); //Enable TOC. settings.EnableToc = true; //Set the style for level 1(H1) items in table of contents. HtmlToPdfTocStyle tocstyleH1 = new HtmlToPdfTocStyle(); // Load the Arabic font from a file PdfFont arabicFont = new PdfTrueTypeFont(@"Data/arial-unicode-ms.ttf", 10, PdfFontStyle.Regular); // Set the TOC style with the Arabic font tocstyleH1.Font = arabicFont; // Set the background color tocstyleH1.BackgroundColor = new PdfSolidBrush(new PdfColor(Color.FromArgb(68, 114, 196))); // Set the foreground color tocstyleH1.ForeColor = PdfBrushes.White; // Set the padding tocstyleH1.Padding = new PdfPaddings(5, 5, 3, 3); settings.Toc.SetItemStyle(1, tocstyleH1); settings.Toc.SetItemStyle(2, tocstyleH1); settings.Toc.SetItemStyle(3, tocstyleH1); settings.Toc.SetItemStyle(4, tocstyleH1); //Assign Blink converter settings to HTML converter. htmlConverter.ConverterSettings = settings; //Convert HTML to PDF document. PdfDocument document = htmlConverter.Convert(Path.GetFullPath(@"Data/input1.html")); //Create a file stream to save the PDF document. using (FileStream fileStream = new FileStream(Path.GetFullPath(@"Output/HTML-to-PDF.pdf"), FileMode.Create, FileAccess.ReadWrite)) { //Save the PDF document document.Save(fileStream); } //Close the PDF document document.Close(true); A complete working sample can be downloaded from HTML-to-PDF-TOC-Arabic By executing the program, you will get the PDF document as follows. Take a moment to peruse the documentation, where you can find converting HTML pages to PDF document with custom style of TOC. You can use fonts that support other languages beyond Arabic for the Table of Contents (TOC) in your HTML to PDF conversion. Please ensure that the chosen font fully supports the required language characters to avoid issues in rendering. Conclusion I hope you enjoyed learning about how to add RTL languages when converting HTML to PDF in .NET Core. You can refer to our ASP.NET Core PDF feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET Core PDF example to understand how to create and manipulate data. For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!
How to Inject Custom CSS to HTML Before Rendering into a PDF document
The Syncfusion HTML to PDF Converter is a .NET library for converting webpages, SVG, MHTML, and HTML to PDF using C#. It is reliable and accurate. The result preserves all graphics, texts, fonts, and the original HTML document or webpage layout. Using this library, you can inject CSS to be applied to HTML or a URL before rendering it into a PDF document. Steps to inject custom CSS to HTML before rendering into a PDF document Create a new .NET console application project. Install the Syncfusion.HtmlToPdfConverter.Net.Windows NuGet package as a reference to your .NET application from NuGet.org. Include the following namespaces in the Program.cs file. using Syncfusion.Drawing; using Syncfusion.HtmlConverter; using Syncfusion.Pdf; Use the following code example to inject custom CSS to be applied to HTML or a URL before rendering it into a PDF document. //Initialize the HTML to PDF converter. HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(); BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings(); //Set the Blink viewport size. blinkConverterSettings.ViewPortSize = new Size(1280, 0); blinkConverterSettings.Margin.All = 30; //Set the custom CSS. blinkConverterSettings.Css = "body {\r\n background-color: lightyellow; \r\n}"; htmlConverter.ConverterSettings = blinkConverterSettings; //Convert the URL to a PDF document. PdfDocument document = htmlConverter.Convert("https://www.google.com"); using (FileStream stream = new FileStream("Sample.pdf", FileMode.Create)) { //Save a PDF document. document.Save(stream); } A complete working sample can be downloaded from Inject-custom-CSS-to-HTML.zip. By executing the program, you will get a PDF document as follows. Take a moment to peruse the documentation, where you can find converting HTML pages to PDF documents along with respective customization options and features. Refer to here to explore the rich set of Syncfusion Essential PDF features. An online sample link for converting HTML to PDF document. Note: Starting with v16.2.0.x, if you reference Syncfusion assemblies from the trial setup or the NuGet feed, include a license key in your projects. Refer to the link to learn how to generate and register the Syncfusion license key in your application and use the components without a trial message.
How to convert HTML to PDF using Blink in AWS Elastic Beanstalk
Steps to convert HTML to PDF using Blink in AWS Elastic Beanstalk Step 1: Create a new C# ASP.NET Core Web Application project. Step 2: In configuration windows, name your project and select Next. Step 3: Install the Syncfusion.HtmlToPdfConverter.Net.Aws NuGet package as a reference to your AWS Elastic Beanstalk project from NuGet.org. Step 4: A default controller named HomeController.cs gets added to create the ASP.NET Core MVC project. Include the following namespaces in that HomeController.cs file. using Syncfusion.Pdf; using Syncfusion.HtmlConverter; using System.IO; Step 5: Add a new button in index.cshtml as follows. @{ Html.BeginForm("BlinkToPDF", "Home", FormMethod.Get); { <div> <input type="submit" value="HTML To PDF" style="width:150px;height:27px" /> <br /> <div class="text-danger"> @ViewBag.Message </div> </div> } Html.EndForm(); } Step 6: Add a new action method named BlinkToPDF in HomeController.cs and include the following code example to convert HTML to PDF document using the Convert method in HtmlToPdfConverter class. The HTML content will be scaled based on the given ViewPortSize property of the BlinkConverterSettings class. public IActionResult BlinkToPDF() { //Initialize HTML to PDF converter. HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink); BlinkConverterSettings settings = new BlinkConverterSettings(); //Set command line arguments to run without the sandbox. settings.CommandLineArguments.Add("--no-sandbox"); settings.CommandLineArguments.Add("--disable-setuid-sandbox"); //Set Blink viewport size. settings.ViewPortSize = new Syncfusion.Drawing.Size(1280, 0); //Assign Blink settings to the HTML converter. htmlConverter.ConverterSettings = settings; //Convert URL to PDF document. PdfDocument document = htmlConverter.Convert("https://www.syncfusion.com"); //Create the memory stream. MemoryStream stream = new MemoryStream(); //Save the document to the memory stream. document.Save(stream); return File(stream.ToArray(), System.Net.Mime.MediaTypeNames.Application.Pdf, "BlinkLinuxDockerAWSBeanstalk.pdf"); } Step 7: Click the Publish to AWS Elastic Beanstalk (Legacy) option by right-clicking the project to publish the application in the AWS Elastic Beanstalk environment. Step 8: Select the Create a new application environment and click Next from Publish to AWS Elastic Beanstalk window. Step 9: Please give any valid name to the environment and URL text box. Check whether the URL link is available while clicking the Check availability option. If the requested link is available means, click NEXT in the Application Environment window. Step 10: Select t3a.micro from the Instance Type text box and select Next in the AWS Options Window. Step 11: Select the Roles and Next option from the Permissions window. Step 12: Click Next from the Application Options window. Step 13: Click Deploy from the Review window. Step 14: Click the URL link to launch the application once the Environment is updated successfully and Environment status is healthy. Now, the webpage will open in the browser. Click the button to convert the webpage to a PDF document. By executing the program, you will get a PDF document as follows. A complete working sample for converting an HTML to PDF using Blink in AWS Elastic Beanstalk can be downloaded from GitHub. Click here to explore the rich set of Syncfusion Essential® PDF features. Take a moment to peruse the documentation for Converting HTML to PDF, where you will find various options for URL to PDF, HTML string to PDF, and Hyperlinks. AWS Elastic Beanstalk: AWSElasticBeanstalkSample.zip See Also: Convert HTML to PDF in AWS Lambda Convert HTML to PDF in Azure Function Convert HTML to PDF in Azure App Service Convert HTML to PDF in Azure Function Linux Convert HTML to PDF in Azure App Service Linux Convert HTML to PDF in docker Starting with v16.2.0.x, if you reference the Syncfusion® assemblies from the trial setup or the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering the Syncfusion® license key in your application to use the components without trail message. I hope you enjoyed learning about how to convert HTML to PDF using Blink in AWS Elastic Beanstalk. You can refer to our ASP.NET Core PDF’s feature tour page to know about its other groundbreaking feature representations. You can also explore our ASP.NET Core PDF example to understand how to present and manipulate data. For current customers, you can check out our ASP.NET Core components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our ASP.NET Core PDF and other ASP.NET Core components. If you have any queries or require clarifications, please let us know in comments below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!
How to convert the WinForms PDF to HTML using the C#?
The Syncfusion® .NET PDF library supports conversion of PDF documents to HTML with the help of XPDF, an open-source viewer library for PDF documents. We have customized XPDF to enable PDF-to-HTML conversion, and our implementation supports preserving HTML content as flow layout with relative positioning. Additionally, we have made improvements to the process of preserving images during the conversion in our Winforms PDF feature tour page. Steps to convert HTML to PDF programmatically: Create a new window Forms Application project. Currently, we do not offer a NuGet package specifically for PDF-to-HTML conversion in applications. To utilize this feature, the following assemblies should be added as references: • Syncfusion.PdfToHtmlConverter.OPX • Syncfusion.PdfToHtmlWrapper   Note:The assemblies for PDF-to-HTML conversion can be found in the "Assemblies" folder of the HTML to PDF sample project.     Then, Install the Syncfusion.Pdf.WinForms NuGet package as reference to your .NET Framework application from NuGet.org. Include the following namespaces in the Form1.cs file.using System; using System.IO; using System.Windows.Forms; using Syncfusion.Pdf.Parsing; using Syncfusion.PdfToHtmlConverter;   Use the following code sample to convert PDF to HTML file.//Initializing PDF to HTML converter. PdfToHtmlConverter converter = new PdfToHtmlConverter();   //Initializing and applying PDF to HTML converter settings. PdfToHtmlConverterSettings setting = new PdfToHtmlConverterSettings(); setting.IsFrame = false; setting.AbsolutePositioning = false; converter.Settings = setting;   //Loading the input PDF document. PdfLoadedDocument loadedDocument = new PdfLoadedDocument("Input.pdf");   //Converting PDF to HTML file. converter.Convert("Input.pdf", "Output.html", loadedDocument.Pages.Count); //Close the PDF document. loadedDocument.Close(true);   By executing the program, you will get the HTML document as follows. A complete work sample can be downloaded from the GitHub. Refer here to explore the rich set of Syncfusion Essential® PDF features. Note:Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion® license key in your application to use the components without trail message.   ConclusionI hope you enjoyed learning about how to convert the WinForms PDF to HTML using the C#.You can refer to our Winforms PDF feature tour page to know about its other groundbreaking feature representations. You can also explore our documentation to understand how to create and manipulate data.For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls.If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!
How to convert HTML to PDF in Azure Functions with Azure Premium plan using Blink?
The Syncfusion® HTML to PDF converter is a .NET Core library for converting webpages, SVG, MHTML, and HTML files to PDF using C#. It uses the popular rendering engine Blink (Google Chrome). It is reliable and accurate. The result preserves all graphics, images, text, fonts, and the layout of the original HTML document or webpage. Using this library, you can convert any HTML strings, URLs, or web pages to PDF in the Azure Functions with Azure Premium plan in Linux. Steps to convert HTML to PDF in the Azure Premium plan Blink rendering engine: Create the Azure function project. In the project configuration window, name your project and select the Create option. Then Select the Azure Functions type and .NET Core version. Install the Syncfusion.HtmlToPdfConverter.Net.Linux NuGet package as a reference to your .NET Core Azure function application from the NuGet.org. Include the following namespaces in Function1.cs file.using Syncfusion.HtmlConverter; using Syncfusion.Pdf; using System.Runtime.InteropServices; Add the following code sample in the Function1 class to convert HTML to PDF using the Blink rendering engine in the Azure Functions Linux Premium.[FunctionName("Function1")] public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext executionContext) { string blinkBinariesPath = string.Empty; MemoryStream ms = new MemoryStream(); log.LogTrace(blinkBinariesPath);  blinkBinariesPath = SetupBlinkBinaries(executionContext);  InstallLinuxPackages(executionContext.FunctionAppDirectory);  //string url = req.Query["url"];   //Initialize the HTML to PDF converter with the Blink rendering engine.    HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);  BlinkConverterSettings settings = new BlinkConverterSettings();   //Set command line arguments to run without sandbox. settings.CommandLineArguments.Add("--no-sandbox"); settings.CommandLineArguments.Add("--disable-setuid-sandbox");  settings.BlinkPath = blinkBinariesPath; //Assign Blink converter settings to the HTML converter. htmlConverter.ConverterSettings = settings;   //Convert URL to PDF. PdfDocument document = htmlConverter.Convert("https://www.syncfusion.com");   //Save and close the PDF document. document.Save(ms); document.Close(); ms.Position = 0; return new FileStreamResult(ms, "application/pdf");  } Add the following helper methods to copy and set permission to the BlinkBinariesLinux folder.   private static string SetupBlinkBinaries(ExecutionContext executionContext) {            string blinkAppDir = Path.Combine(executionContext.FunctionAppDirectory, "bin/runtimes/linux/native"); string tempBlinkDir = Path.GetTempPath(); string chromePath = Path.Combine(tempBlinkDir, "chrome");             if (!File.Exists(chromePath)) { CopyFilesRecursively(blinkAppDir, tempBlinkDir);  SetExecutablePermission(tempBlinkDir);  } return tempBlinkDir; }   private static void CopyFilesRecursively(string sourcePath, string targetPath)  { //Create all the directories from the source to the destination path. foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories)) {  Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath)); }    //Copy all the files from the source path to the destination path.  foreach (string newPath in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories)) {  File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true); } }   [DllImport("libc", SetLastError = true, EntryPoint = "chmod")] internal static extern int Chmod(string path, FileAccessPermissions mode);   private static void SetExecutablePermission(string tempBlinkDir) { FileAccessPermissions ExecutableFilePermissions = FileAccessPermissions.UserRead | FileAccessPermissions.UserWrite | FileAccessPermissions.UserExecute | FileAccessPermissions.GroupRead | FileAccessPermissions.GroupExecute | FileAccessPermissions.OtherRead | FileAccessPermissions.OtherExecute;   string[] executableFiles = new string[] { "chrome", "chrome_sandbox" }; foreach (string executable in executableFiles) { var execPath = Path.Combine(tempBlinkDir, executable);   if (File.Exists(execPath)) { var code = Function1.Chmod(execPath, ExecutableFilePermissions); if (code != 0) { throw new Exception("Chmod operation failed"); } } } } Include the below Enum in the Function1.cs file.[Flags] internal enum FileAccessPermissions : uint { OtherExecute = 1, OtherWrite = 2, OtherRead = 4,   GroupExecute = 8, GroupWrite = 16, GroupRead = 32,   UserExecute = 64, UserWrite = 128, UserRead = 256 } The Azure Function app is currently in read-only mode, and the external files do not have the authorization to execute while the function app is being deployed. To get around this limitation, we moved the requirements shell file to a temporary directory and then granted sufficient execute access to install the Linux package.private static void InstallLinuxPackages(string functionAppDirectory) { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) {  return; }  FileAccessPermissions ExecutableFilePermissions = FileAccessPermissions.UserRead | FileAccessPermissions.UserWrite | FileAccessPermissions.UserExecute | FileAccessPermissions.GroupRead | FileAccessPermissions.GroupExecute | FileAccessPermissions.OtherRead | FileAccessPermissions.OtherExecute;   //Install the dependencies packages for HTML to PDF conversion in Linux string shellFilePath = Path.Combine(functionAppDirectory, "data"); string tempBlinkDir = Path.GetTempPath(); string dependenciesPath = Path.Combine(tempBlinkDir, "dependenciesInstall.sh"); if (!File.Exists(dependenciesPath)) { CopyFilesRecursively(shellFilePath, tempBlinkDir); var execPath = Path.Combine(tempBlinkDir, "dependenciesInstall.sh");   if (File.Exists(execPath)) { var code = Function1.Chmod(execPath, ExecutableFilePermissions); if (code != 0) { throw new Exception("Chmod operation failed"); } } Process process = new Process { StartInfo = new ProcessStartInfo { FileName = "/bin/bash", Arguments = "-c " + execPath, CreateNoWindow = true,  UseShellExecute = false, } }; process.Start(); process.WaitForExit(); } } Set Copy to Output Directory as “Copy if newer” to the dependenciesInstall.sh file. Publish to Azure Functions Linux Follow the given steps to publish to Azure Functions Linux: Right-click the project and select Publish. Then, create a new profile in the Publish Window and you can create the Azure Function App service with a Premium plan. Select existing or create a new Azure function. After creating the profile, click the Publish button.   Now, go to the Azure portal and select the App Services. After running the service, click Get function URL > Copy.    Then, paste it into the new browser tab. You will get the PDF document as follows: A complete working sample can be downloaded from the HTML to PDF Azure Premium. Take a moment to peruse the documentation where you can find converting HTML pages to PDF documents along with respective customization options and features. Click here to explore the rich set of Syncfusion Essential® PDF features. An online sample link to convert HTML to PDF. Note:Starting with v16.2.0.x, if you reference Syncfusion® assemblies from the trial setup or from the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering the Syncfusion® license key in your application to use the components without a trail message.  
How to convert HTML to PDF in AWS Lambda with NET 6 Container Image?
The Syncfusion® HTML to PDF converter is a .NET Core PDF library for converting webpages, SVG, MHTML, and HTML to PDF using C#. It is reliable and accurate. Using this library, you can convert HTML to PDF in AWS Lambda with docker image using Blink. Setting up the AWS Toolkit for Visual Studio: You can create an AWS account by referring to this link. Download and install the AWS Toolkit for Visual Studio, you can download the AWS toolkit from this link. The Toolkit can be installed from Tools/Extension and updates options in Visual Studio. Refer to the following steps to convert HTML to PDF in AWS Lambda with docker image: Create an AWS Lambda function to convert HTML to PDF and publish it to AWS. Invoke the AWS Lambda function in your main application using AWS SDKs. Steps to convert HTML to PDF in AWS Lambda with docker image: Create a new AWS Lambda project with Tests as follows: Create a project name and select location.   Select Blueprint as .NET 6 (Container Image) Function and click Finish. Install the Syncfusion.HtmlToPdfConverter.Net.Aws and AWSSDK.Lambda NuGet package as a reference to your AWS lambda project from NuGet.org.   Using the following namespaces in the Function.cs file.using Syncfusion.HtmlConverter; using Syncfusion.Pdf; using System.IO;   Add the following code sample in Function.cs to create a PDF document.public string FunctionHandler(string input, ILambdaContext context) {    //Initialize HTML to PDF converter with the Blink rendering engine.    HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);           BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();    blinkConverterSettings.BlinkPath = Path.GetFullPath("BlinkBinariesAws");    blinkConverterSettings.CommandLineArguments.Add("--no-sandbox");    blinkConverterSettings.CommandLineArguments.Add("--disable-setuid-sandbox");    blinkConverterSettings.AdditionalDelay = 3000; htmlConverter.ConverterSettings = blinkConverterSettings;      //Convert the HTML string to PDF.    PdfDocument document = htmlConverter.Convert(input, PathToFile());             //Save the document into a stream.    MemoryStream memoryStream = new MemoryStream();      //Save and close the PDFDocument.    document.Save(memoryStream);    document.Close(true);      string base64 = Convert.ToBase64String(memoryStream.ToArray());    memoryStream.Close();    memoryStream.Dispose();   return base64; }   public static string PathToFile() {    string? path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);    if (string.IsNullOrEmpty(path))    {       path = Environment.OSVersion.Platform == PlatformID.Unix ? @"/" : @"\";    }    return Environment.OSVersion.Platform == PlatformID.Unix ? string.Concat(path.Substring(5), @"/") : string.Concat(path.Substring(6), @"\"); }   Create a new folder as Helper and add a class file as AWSHelper.cs. Add the following namespaces and code samples in AWSHelper class to invoke the published AWS Lambda function using the function name and access keys.Using Amazon.Lambda; using Amazon.Lambda.Model; using Newtonsoft.Json;   public class AWSHelper {    public static async Task<byte[]> RunLambdaFunction(string html)    {       try       {          var AwsAccessKeyId = "awsaccessKeyID";          var AwsSecretAccessKey = "awsSecretAccessKey";            AmazonLambdaClient client = new AmazonLambdaClient(AwsAccessKeyId, AwsSecretAccessKey, Amazon.RegionEndpoint.USEast1);          InvokeRequest invoke = new InvokeRequest          {             FunctionName = "AWSLambdaDockerContainer",             InvocationType = InvocationType.RequestResponse,             Payload = Newtonsoft.Json.JsonConvert.SerializeObject(html)          };          //Get the InvokeResponse from the client InvokeRequest.          InvokeResponse response = await client.InvokeAsync(invoke);            //Read the response stream.          Console.WriteLine($"Response: {response.LogResult}");          Console.WriteLine($"Response: {response.StatusCode}");          Console.WriteLine($"Response: {response.FunctionError}");          var stream = new StreamReader(response.Payload);          JsonReader reader = new JsonTextReader(stream);          var serilizer = new JsonSerializer();          var responseText = serilizer.Deserialize(reader);            //Convert Base64String into a PDF document.          return Convert.FromBase64String(responseText.ToString());       }       catch (Exception ex)       {           Console.WriteLine($"Exception Occured HTMLToPDFHelper: {ex}");       }    return Convert.FromBase64String("");    } }   Right-click the project and select Publish to AWS Lambda. Create a new AWS profile in the Upload Lambda Function Window. After creating the profile, add a name for the Lambda function to publish. Then, click Next.           In the Advanced Function Details window, specify the Role Name as based on AWS Managed policy. After selecting the role, click the Upload button to deploy your application. After deploying the application, Sign in your AWS account and you can see the published Lambda function in AWS console. Refer to the following steps to invoke the AWS Lambda function from the Test application: Add the following code to invoke the AWS lambda function with HTML string from the Function Test.public class FunctionTest {     [Fact]     public void HtmlToPDFFunction()     {         string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);         string filePath = Environment.OSVersion.Platform == PlatformID.Unix ? string.Concat(path.Substring(5), @"/") : string.Concat(path.Substring(6), @"\");           var html = File.ReadAllText($"{filePath}/HtmlSample.html");         byte[] base64 = null;         base64 = AWSHelper.RunLambdaFunction(html).Result;           FileStream file = new FileStream($"{filePath}/file{DateTime.Now.Ticks}.pdf", FileMode.Create, FileAccess.Write);         var ms = new MemoryStream(base64);         ms.WriteTo(file);         file.Close();         ms.Close();     } } Right click the test application and select Run Tests. By executing the program, you will get the PDF document as follows. Click here to explore the rich set of Syncfusion Essential® PDF features.   Take a moment to peruse the documentation for Converting HTML to PDF, where you will find various options for URL to PDF, HTML string to PDF, and Hyperlinks. AWS Lambda: AWSLambdaDockerContainer.zip See Also: Convert HTML to PDF in AWS Lambda Convert HTML to PDF in Azure Function Convert HTML to PDF in Azure App Service Convert HTML to PDF in Azure Function Linux Convert HTML to PDF in Azure App Service Linux Convert HTML to PDF in docker   Note:Starting with v16.2.0.x, if you reference the Syncfusion® assemblies from the trial setup or the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering the Syncfusion® license key in your application to use the components without trail message.   Conclusion I hope you enjoyed learning about how to convert HTML to PDF in AWS Lambda with NET 6 Container Image. You can refer to our ASP.NET Core PDF’s feature tour page to know about its other groundbreaking feature representations. You can also explore our ASP.NET Core PDF example to understand how to present and manipulate data. For current customers, you can check out our ASP.NET Core components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our ASP.NET Core PDF and other ASP.NET Core components. If you have any queries or require clarifications, please let us know in comments below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!  
How to convert HTML to ASP.NET Core PDF in AWS Lambda?
The Syncfusion® HTML to PDF converter is a .NET library for converting webpages, SVG, MHTML, and HTML to PDF using C#. It is reliable and accurate. Using this library, you can convert HTML to PDF in AWS Lambda using Blink in our ASP.NET Core PDF feature tour page. Setting up the AWS Toolkit for Visual Studio: You can create an AWS account by referring to this link. Download and install the AWS Toolkit for Visual Studio, you can download the AWS toolkit from this link. The Toolkit can be installed from Tools/Extension and updates options in Visual Studio. Refer to the following steps to convert HTML to PDF in AWS Lambda: Create an AWS Lambda function to convert HTML to PDF and publish it to AWS. Invoke the AWS Lambda function in your main application using AWS SDKs. Steps to convert HTML to PDF in AWS Lambda: Create a new AWS Lambda project as follows: Create a project name and select location.   Select Blueprint as Empty Function and click Finish. Install the Syncfusion.HtmlToPdfConverter.Net.Aws NuGet package as a reference to your AWS lambda project from NuGet.org. Using the following namespaces in the Function.cs file.using Syncfusion.HtmlConverter; using Syncfusion.Pdf; using System.IO;   Add the following code snippet in Function.cs to create a PDF document.//Initialize HTML to PDF converter with Blink rendering engine. HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();   //Convert URL to PDF. PdfDocument document = htmlConverter.Convert(input);   //Save the document into stream. MemoryStream memoryStream = new MemoryStream();   //Save and Close the PDFDocument. document.Save(memoryStream); document.Close(true);   return Convert.ToBase64String(memoryStream.ToArray());   Right-click the project and select Publish to AWS Lambda. Create a new AWS profile in the Upload Lambda Function Window. After creating the profile, add a name for the Lambda function to publish. Then, click Next.           In the Advanced Function Details window, specify the Role Name as based on AWS Managed policy. After selecting the role, click the Upload button to deploy your application. After deploying the application, Sign in your AWS account and you can see the published Lambda function in AWS console. Refer to the following steps to invoke the AWS Lambda function from the console application: Create a new console project. Create a project name and select folder path.   Install the AWSSDK.Core, AWSSDK.Lambda and Newtonsoft.Json package as a reference to your main application from the NuGet.org. Include the following namespaces in Program.cs file.using Amazon; using Amazon.Lambda; using Amazon.Lambda.Model; using Newtonsoft.Json; using System.IO;   Add the following code snippet in Program class to invoke the published AWS Lambda function using the function name and access keys.//Create a new AmazonLambdaClient AmazonLambdaClient client = new AmazonLambdaClient("awsaccessKeyID", "awsSecreteAccessKey", RegionEndpoint.USEast1);   //Create new InvokeRequest with the published function name InvokeRequest invoke = new InvokeRequest {   FunctionName = "AwsLambdaFunctionHtmlToPdfConversion",   InvocationType = InvocationType.RequestResponse,   Payload = "\" https://www.google.co.in/ \"" }; //Get the InvokeResponse from client InvokeRequest InvokeResponse response = client.Invoke(invoke);   //Read the response stream var stream = new StreamReader(response.Payload); JsonReader reader = new JsonTextReader(stream); var serilizer = new JsonSerializer(); var responseText = serilizer.Deserialize(reader);   //Convert Base64String into PDF document byte[] bytes = Convert.FromBase64String(responseText.ToString()); FileStream fileStream = new FileStream("Sample.pdf", FileMode.Create); BinaryWriter writer = new BinaryWriter(fileStream); writer.Write(bytes, 0, bytes.Length); writer.Close(); System.Diagnostics.Process.Start("Sample.pdf");   By executing the program, you will get the PDF document as follows. Click here to explore the rich set of Syncfusion Essential® PDF features.   Take a moment to peruse the documentation for Converting HTML to PDF, where you will find various options for URL to PDF, HTML string to PDF, and Hyperlinks. AWS Lambda: HtmlToPDFAWSLambdaBlink.zip Console sample: ClientHtmlToPDFConversion.zip See Also: Convert HTML to PDF in Azure Function Convert HTML to PDF in Azure App Service Convert HTML to PDF in Azure Function Linux Convert HTML to PDF in Azure App Service Linux   Note:Starting with v16.2.0.x, if you reference the Syncfusion® assemblies from the trial setup or the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering the Syncfusion® license key in your application to use the components without trail message.    ConclusionI hope you enjoyed learning about how to convert HTML to ASP.NET Core PDF in AWS Lambda.You can refer to our ASP.NET Core PDF feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET Core PDF Example to understand how to create and manipulate data.For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls.If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!
How to set different margin settings in HTML when converting to PDF using C# in ASP.NET MVC?
Syncfusion® HTML to PDF for .NET is used to convert webpages, SVG, MHTML, and HTML to PDF. Using this library, you can set different page margins in HTML when converting to PDF document. Steps to set different margin settings in HTML to PDF conversion programmatically: Create a new ASP.NET MVC application project. Install the Syncfusion.HtmlToPdfConverter.AspNet.Mvc5 NuGet package as a reference to your .NET Framework applications from NuGet.org. A default controller with name HomeController.cs gets added on creation of ASP.NET MVC project. Include the following namespaces in that HomeController.cs file. C# using Syncfusion.Pdf; using Syncfusion.HtmlConverter; using System.Drawing; A default action method named Index will be presented in HomeController.cs. Right-click this action method and select Go To View, where you will be directed to its associated view page Index.cshtml. Add a new button in the Index.cshtml as follows.@using (Html.BeginForm("ConvertHtmlToPdf", "Home", FormMethod.Post)) {     <input type="submit" value="Convert" /> Add a new action method named ConvertHtmlToPdf in HomeController.cs and include the following code snippet to set different margin settings in the conversion of HTML to PDF file and download it. C# //Input HTML URL to convert string url = Server.MapPath("~/Data/TableHTML.htm");   //Initialize HTML to PDF converter HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();   //Initialize Blink converter settings BlinkConverterSettings settings = new BlinkConverterSettings();   //Enable JavaScript settings.EnableJavaScript = true; settings.MediaType = MediaType.Print;   //Disable split images and text lines settings.SplitImages = false; settings.SplitTextLines = false;   //Set blink view port size settings.ViewPortSize = new Size(1200, 0);   //Set PDF page margin settings.Margin = new Syncfusion.Pdf.Graphics.PdfMargins { Top = 40, Left = 30, Right = 40, Bottom = 50 }; htmlConverter.ConverterSettings = settings;   //Convert URL to PDF document PdfDocument document = htmlConverter.Convert(url);   //Save and close the PDF document document.Save("Output.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save); document.Close(true); return null; A complete working sample can be downloaded from DifferentMarginSettingsHtmlToPDF.zip. By executing the program, you will get the PDF file as follows. Take a moment to peruse the documentation, where you can find converting HTML pages to PDF document along with respective customization options and features. Refer here to explore the rich set of Syncfusion Essential® PDF features. An online sample link for Converting HTML to PDF. Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion® license key in your application to use the components without trail message.  Conclusion I hope you enjoyed learning about how to set different margin settings in HTML when converting to PDF using C# in ASP.NET MVC.You can refer to our ASP.NET MVC PDF feature tour page to know about its other groundbreaking feature representations. You can also explore our documentation to understand how to present and manipulate data.For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other components.If you have any queries or require clarifications, please let us know in comments below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!
Convert HTML to PDF in Azure Functions 4.0 in ASP.NET Core?
Syncfusion® HTML to PDF converter for ASP.NET Core PDF used to convert web pages, and HTML to PDF. Using this library, you can convert any HTML strings or URL or web pages to PDF in Azure Functions 4.0(NET 6). In this tutorial, we will illustrate the conversion of HTML to PDF using C# with advanced WebKit rendering engine. In addition, our HTML to PDF converter will work seamlessly in various platforms like Azure cloud or web apps, Amazon Web Service (AWS), Docker, WinForms, WPF, ASP.NET MVC, ASP.NET Core with Windows, Linux, and MacOS. Steps to convert HTML to PDF in Azure Functions 4.0 Create an Azure Functions projects.   Select framework to Azure Functions V4 (.NET 6) and select HTTP triggers as follows.   Install the Syncfusion.HtmlToPdfConverter.Net.Linux NuGet package as a reference to the project. Include the following namespace in Functions1.cs file to convert the HTML to PDF using C#.using Syncfusion.HtmlConverter; using Syncfusion.Pdf; using System.Runtime.InteropServices; C#   Add the following code snippet in Function1 class to convert HTML to PDF in Azure Functions V4.[FunctionName("Function1")] public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext executionContext) {      string blinkBinariesPath = string.Empty;      try      {      blinkBinariesPath = SetupBlinkBinaries(executionContext);      }      catch      {          throw new Exception("BlinkBinaries initialization failed");      }        string url = req.Query["url"];        //Initialize the HTML to PDF converter with the Blink rendering engine.      HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);      BlinkConverterSettings settings = new BlinkConverterSettings();        //Set command line arguments to run without sandbox.      settings.CommandLineArguments.Add("--no-sandbox");      settings.CommandLineArguments.Add("--disable-setuid-sandbox");        settings.BlinkPath = blinkBinariesPath;        //Assign Blink Converter settings to the HTML converter      htmlConverter.ConverterSettings = settings;        //Convert URL to PDF      PdfDocument document = htmlConverter.Convert(url);        MemoryStream ms = new MemoryStream();           //Save and close the PDF document       document.Save(ms);      document.Close();        ms.Position = 0;        return new FileStreamResult(ms, "application/pdf"); } Add the following helper methods to copy and set permission to the BlinkBinariesLinux folder. private static string SetupBlinkBinaries(ExecutionContext executionContext) { string blinkAppDir = Path.Combine(executionContext.FunctionAppDirectory, "BlinkBinariesLinux"); string tempBlinkDir = Path.GetTempPath(); string chromePath = Path.Combine(tempBlinkDir, "chrome");   if (!File.Exists(chromePath)) {        CopyFilesRecursively(blinkAppDir, tempBlinkDir);        SetExecutablePermission(tempBlinkDir); } return tempBlinkDir; }     private static void CopyFilesRecursively(string sourcePath, string targetPath) { //Create all the directories from the source to the destination path. foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories)) {     Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath)); }   //Copy all the files from the source path to the destination path. foreach (string newPath in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories)) {     File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true); } }   [DllImport("libc", SetLastError = true, EntryPoint = "chmod")] internal static extern int Chmod(string path, FileAccessPermissions mode);   private static void SetExecutablePermission(string tempBlinkDir) { FileAccessPermissions ExecutableFilePermissions = FileAccessPermissions.UserRead | FileAccessPermissions.UserWrite | FileAccessPermissions.UserExecute | FileAccessPermissions.GroupRead | FileAccessPermissions.GroupExecute | FileAccessPermissions.OtherRead | FileAccessPermissions.OtherExecute;   string[] executableFiles = new string[] { "chrome", "chrome_sandbox" };   foreach (string executable in executableFiles) {     var execPath = Path.Combine(tempBlinkDir, executable);       if (File.Exists(execPath))     {         var code = Function1.Chmod(execPath, ExecutableFilePermissions);         if (code != 0)         {             throw new Exception("Chmod operation failed");         }     }     } } Include the below enum in the Function1.cs file. [Flags] internal enum FileAccessPermissions : uint { OtherExecute = 1, OtherWrite = 2, OtherRead = 4,   GroupExecute = 8, GroupWrite = 16, GroupRead = 32,   UserExecute = 64, UserWrite = 128, UserRead = 256 }   Public to Azure Functions Linux: Right-click the project and select Publish. Then, create a new profile in the Publish Window. The Blink rendering engine will work in consumption plan. So, you can create the Azure Function App service with a consumption plan. After creating the profile, click the Publish button. Now, go to the Azure portal and select the App Services. After running the service, click Get function URL > Copy. Include the URL as a query string in the URL. Then, paste it into the new browser tab. You will get the PDF document as follows. Example: https://htmltopdfazurefunctionblink.azurewebsites.net/api/Function1?code=aYCeymbJeHMGIwEEIuCIcNe….​&url=https://www.syncfusion.com A complete working sample can be downloaded from HtmlToPdf_AzureFunctions4.0.zip.   Take a moment to peruse the documentation, where you can find converting HTML pages to PDF document along with respective customization options and features.   Click here to explore the rich set of Syncfusion Essential® PDF features.   An online sample link to convert HTML to PDF.ConclusionI hope you enjoyed learning about how to convert HTML to PDF in Azure Functions 4.0.You can refer to our ASP.NET Core PDF's feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET PDF example to understand how to create and manipulate data.For current customers, you can check out our Document Processing Libraries from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our controls.If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!
How to consume the HTML to PDF conversion from Azure App Service (Windows) via Azure functions (Linux)?
The Syncfusion® HTML to PDF converter is a .NET library that uses C# for converting webpages, SVG, MHTML, and HTML to PDF. It is reliable and accurate. The result preserves all graphics, images, text, fonts, and the layout of the original HTML document or webpage. Due to GDI limitations in Azure App Service windows, the Blink rendering engine does not support HTML conversion directly. As a workaround, we can use Azure functions on Linux to perform HTML to PDF conversion using Blink in the Azure App Service on Windows. How to use Blink HTML to PDF conversion in Azure App Service windows using Azure functions on Linux:   To achieve this, we need to create an Azure function app and publish the function to Azure Function Linux. Get the function URL and ensure that the functions are working properly after publishing the Azure Function App. Kindly refer the following KB documentation to create and publish the Azure function Linux with the Blink rendering engine: https://www.syncfusion.com/kb/12908/how-to-convert-html-to-pdf-using-blink-in-azure-functions-linux   Create a new ASP.NET Core MVC application. Install the Syncfusion.Pdf.Net.Core NuGet package as a reference to your project from NuGet.org.     Add a Convert To PDF button in index.cshtml.@{ Html.BeginForm("ConvertToPDF ", "Home", FormMethod.Post);         {             <input type="submit" value="Convert To PDF" class=" btn" />         } }   Include the following namespaces and code snippet in controller for calling your azure function URL from your azure app service:   Note:you can load the converted PDF document and perform the post processing functionalities such as adding encryption, digital signature etc., to the output PDF document.   // [C# Code] using System.IO; using Syncfusion.Pdf;   using Microsoft.AspNetCore.Hosting;   public IActionResult ConvertToPDF() { //Add the Azure function URL to convert HTML to PDF string functionURL = "https://binkhtmltopdflinuxappp.azurewebsites.net/api/Function1?";   //URL to convert to PDF document string url = "https://www.syncfusion.com";   string  functionUrlwithParameter = functionURL + "url=" + url;   //Create HttpWebRequest with azure functions URL.    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(functionUrlwithParameter);             //Gets the response from the Azure Functions. HttpWebResponse res = (HttpWebResponse)req.GetResponse();   MemoryStream stream = new MemoryStream(); res.GetResponseStream().CopyTo(stream);            PdfLoadedDocument loadedDocument = new PdfLoadedDocument(stream);   //Document security. PdfSecurity security = loadedDocument.Security;   security.Algorithm = PdfEncryptionAlgorithm.AES;   security.OwnerPassword = "syncfusion"; security.UserPassword = "password";   loadedDocument.Save(stream); loadedDocument.Close();   // Save the response stream as PDF document. return File(stream.ToArray(), "application/pdf", "Output.pdf"); }          Refer to the following steps to publish as Azure App Windows: Right-click the project and select Publish.   Create a new profile in publish target window.   Create an App service using Azure subscription and select a hosting plan.   After creating a profile, click the publish button. The published webpage will now be shown in the browser. Click Convert to PDF to convert the Google webpage to a PDF. A complete work sample for consuming the HTML to PDF conversion from Azure App Service (windows) via Azure functions (linux) can be downloaded from HtmlToPDF_Azure.zip Take a moment to peruse the documentation, where you will find other Blink rendering engines supported by Syncfusion .NET PDF library for converting HTML pages to PDF document along with respective customization options and features. Click here to explore the rich set of Syncfusion Essential® PDF features. ​An online sample link to convert HTML to PDF. HTML to PDF conversion in Linux docker container HTML to PDF conversion in Azure Function HTML to PDF conversion in ASP .Net Core Linux HTML to PDF conversion in Azure App Service Note:Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion® license key in your application to use the components without trail message.  
How to convert HTML to PDF in Blazor using C#?
The Syncfusion HTML to PDF converter is a .NET library for converting webpages, SVG, MHTML, and HTML to PDF using C#. It is reliable and accurate. The result preserves all graphics, images, text, fonts, and the layout of the original HTML document or webpage. Using this library, you can convert an HTML to PDF in Blazor framework using C#. Steps to convert HTML to PDF in Blazor application Create a new C# Blazor application project. Select Blazor App from the template and click the Next button. Now, the project configuration window appears. Click Create button to create a new project with the default project configuration. Choose Blazor Server App from the dashboard and click Create button to create a new Blazor server application. Install the  Syncfusion.HtmlToPdfConverter.Net.Windows NuGet package as a reference to your Blazor application from nuget.org. Create a new class file named ExportService under Data folder and include the following namespaces in the file.   Add the following namespace in ExportService class. C# using Syncfusion.HtmlConverter; using Syncfusion.Pdf; using System.IO;   Use the following code sample to convert HTML to PDF document. //Export HTML to PDF document. public MemoryStream CreatePdf() {    //Initialize HTML to PDF converter    HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter()      //Convert URL to PDF document    PdfDocument document = htmlConverter.Convert("https://www.google.com");      MemoryStream stream = new MemoryStream();      //Save and close the PDF document    document.Save(stream);    document.Close(true);      return stream; }   Register your service in the ConfigureServices method available in the Startup.cs class as follows.public void ConfigureServices(IServiceCollection services) {     services.AddRazorPages();     services.AddServerSideBlazor();     services.AddSingleton<WeatherForecastService>();     services.AddSingleton<ExportService>(); }   Inject ExportService in-to FetchData.razor using the following code.@inject ExportToFileService exportService @inject Microsoft.JSInterop.IJSRuntime JS @using  System.IO;   Create a button in the FetchData.razor using the following code.<button class="btn btn-primary" @onclick="@ExportToPdf">Export to PDF</button>     Add the ExportToPdf method in FetchData.razor page to call the export service.@functions {     protected async Task ExportToPdf()     {         using (MemoryStream excelStream = PDFExportService.CreatePdf(forecasts))         {             await JS.SaveAs("HTMLToPDF.pdf", excelStream.ToArray());         }     } } Create a class file with FileUtil name and add the following code to invoke the JavaScript action to download the file in the browser.public static class FileUtil {     public static ValueTask<object> SaveAs(this IJSRuntime js, string filename, byte[] data)        => js.InvokeAsync<object>(            "saveAsFile",            filename,            Convert.ToBase64String(data)); }   Add the following JavaScript function in the Host.cshtml available under the Pages folder.<script type="text/javascript">     function saveAsFile(filename, bytesBase64) {             if (navigator.msSaveBlob) {                 //Download document in Edge browser                 var data = window.atob(bytesBase64);                 var bytes = new Uint8Array(data.length);                 for (var i = 0; i < data.length; i++) {                     bytes[i] = data.charCodeAt(i);                 }                 var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });                 navigator.msSaveBlob(blob, filename);             }             else {         var link = document.createElement('a');         link.download = filename;         link.href = "data:application/octet-stream;base64," + bytesBase64;         document.body.appendChild(link); // Needed for Firefox         link.click();         document.body.removeChild(link);     }         } </script>     By executing the program, you will get the following output in the browser. Click the Export to PDF button, and you will get the PDF document with the following output. A complete work sample for converting an HTML to PDF in the Blazor framework can be downloaded from BlazorHTMLToPDF.Zip. Take a moment to peruse the documentation, where you can find converting HTML pages to PDF document along with respective customization options and features. Refer here to explore the rich set of Syncfusion Essential PDF features. An online sample link for Converting HTML to PDF. Note:Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion license key in your application to use the components without trail message.  
How to resolve the issue "Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0 or one of its dependencies" in HTML to PDF conversion using the Blink rendering engine
You can refer to the Newtonsoft.Json assembly or package with version 6.0.8 or above in the application for converting HTML to PDF using a Blink rendering engine. But, you need to specify the assembly version of Newtonsoft.Json in the App.config file of the application. Please find the code sample for specifying the Newtonsoft.Json assembly in the App.config file.  Note:If the project is a web application then the assembly binding redirect code sample should be updated in the web.config file.    When installing the Newtonsoft.Json assembly from NuGet package, it will automatically include the assembly binding redirect code sample in the App.config or web.config file.  <runtime>      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">        <dependentAssembly>          <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />          <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />        </dependentAssembly>      </assemblyBinding>    </runtime>      Note:You need to modify the newVersion attribute of the bindingRedirect tag in the App.config or web.config file according to the version of the Newtonsoft.Json assembly referred.    A complete work sample can be downloaded from BlinkHtmlToPdf.zip.Click here to explore a rich set of the Syncfusion Essential PDF features.An online sample link to convert HTML to PDF.
How to convert HTML to PDF with Blink using C#
The Syncfusion HTML to PDF converter is a .NET library for converting webpages, SVG, MHTML, and HTML to PDF using C#. It is reliable and accurate. The result preserves all graphics, images, texts, fonts, and the layout of the original HTML document or webpage. Using this library, you can convert HTML to PDF document using Blink rendering engine in C#. Steps to convert HTML to PDF document programmatically:  Create a new C# console application project. Install the Syncfusion.HtmlToPdfConverter.WinForms NuGet package as a reference to your .NET Framework application from NuGet.org. Include the following namespace in the Program.cs file. C# using Syncfusion.HtmlConverter; using Syncfusion.Pdf;   Use the following code to convert HTML to PDF document. C# //Initialize HTML to PDF converter HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();   //Convert HTML to PDF PdfDocument document = htmlConverter.Convert("http://www.google.com/");   //Save and Close the PDF document document.Save("HTMLToPDF.pdf"); document.Close(true);   //This will open the PDF file so, the result will be seen in default PDF viewer System.Diagnostics.Process.Start("HTMLToPDF.pdf");   You can download the complete working sample from HTMLToPDFSample.zip. By executing the program, you will get the PDF document as follows. Take a moment to peruse the documentation, where you can find converting HTML pages to PDF document along with respective customization options and features. Refer here to explore the rich set of Syncfusion Essential PDF features. An online sample link for Converting HTML to PDF. Note:Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion license key in your application to use the components without trail message.  
How to convert HTML to PDF in Azure Functions 4.0 with ASP.NET Core PDF?
Syncfusion® HTML to PDF converter for our ASP.NET Core PDF Library's feature tour page  used to convert web pages, and HTML to PDF. Using this library, you can convert any HTML strings or URL or web pages to PDF in Azure Functions 4.0(NET 6). In this tutorial, we will illustrate the conversion of HTML to PDF using C# with advanced Blink rendering engine. In addition, our HTML to PDF converter will work seamlessly in various platforms like Azure cloud or web apps, Amazon Web Service (AWS), Docker, WinForms, WPF, ASP.NET MVC, ASP.NET Core with Windows, Linux, and MacOS. Steps to convert HTML to PDF in Azure Functions 4.0 Create an Azure Functions projects.   Select framework to Azure Functions V4 (.NET 6) and select HTTP triggers as follows.   Install the Syncfusion.HtmlToPdfConverter.Net.Linux NuGet package as a reference to the project. Include the following namespace in Functions1.cs file to convert the HTML to PDF using C#.using Syncfusion.HtmlConverter; using Syncfusion.Pdf; using System.Runtime.InteropServices; C#   Add the following code snippet in Function1 class to convert HTML to PDF in Azure Functions V4.[FunctionName("Function1")] public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext executionContext) {      string blinkBinariesPath = string.Empty;      try      {      blinkBinariesPath = SetupBlinkBinaries(executionContext);      }      catch      {          throw new Exception("BlinkBinaries initialization failed");      }        string url = req.Query["url"];        //Initialize the HTML to PDF converter with the Blink rendering engine.      HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);      BlinkConverterSettings settings = new BlinkConverterSettings();        //Set command line arguments to run without sandbox.      settings.CommandLineArguments.Add("--no-sandbox");      settings.CommandLineArguments.Add("--disable-setuid-sandbox");        settings.BlinkPath = blinkBinariesPath;        //Assign Blink Converter settings to the HTML converter      htmlConverter.ConverterSettings = settings;        //Convert URL to PDF      PdfDocument document = htmlConverter.Convert(url);        MemoryStream ms = new MemoryStream();           //Save and close the PDF document       document.Save(ms);      document.Close();        ms.Position = 0;        return new FileStreamResult(ms, "application/pdf"); } Add the following helper methods to copy and set permission to the BlinkBinariesLinux folder. private static string SetupBlinkBinaries(ExecutionContext executionContext) { string blinkAppDir = Path.Combine(executionContext.FunctionAppDirectory, "bin/runtimes/linux/native"); string tempBlinkDir = Path.GetTempPath(); string chromePath = Path.Combine(tempBlinkDir, "chrome");   if (!File.Exists(chromePath)) {        CopyFilesRecursively(blinkAppDir, tempBlinkDir);        SetExecutablePermission(tempBlinkDir); } return tempBlinkDir; }     private static void CopyFilesRecursively(string sourcePath, string targetPath) { //Create all the directories from the source to the destination path. foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories)) {     Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath)); }   //Copy all the files from the source path to the destination path. foreach (string newPath in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories)) {     File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true); } }   [DllImport("libc", SetLastError = true, EntryPoint = "chmod")] internal static extern int Chmod(string path, FileAccessPermissions mode);   private static void SetExecutablePermission(string tempBlinkDir) { FileAccessPermissions ExecutableFilePermissions = FileAccessPermissions.UserRead | FileAccessPermissions.UserWrite | FileAccessPermissions.UserExecute | FileAccessPermissions.GroupRead | FileAccessPermissions.GroupExecute | FileAccessPermissions.OtherRead | FileAccessPermissions.OtherExecute;   string[] executableFiles = new string[] { "chrome", "chrome_sandbox" };   foreach (string executable in executableFiles) {     var execPath = Path.Combine(tempBlinkDir, executable);       if (File.Exists(execPath))     {         var code = Function1.Chmod(execPath, ExecutableFilePermissions);         if (code != 0)         {             throw new Exception("Chmod operation failed");         }     }     } } Include the below enum in the Function1.cs file. [Flags] internal enum FileAccessPermissions : uint { OtherExecute = 1, OtherWrite = 2, OtherRead = 4,   GroupExecute = 8, GroupWrite = 16, GroupRead = 32,   UserExecute = 64, UserWrite = 128, UserRead = 256 }   Public to Azure Functions Linux: Right-click the project and select Publish. Then, create a new profile in the Publish Window. The Blink rendering engine will work in consumption plan. So, you can create the Azure Function App service with a consumption plan. After creating the profile, click the Publish button. Now, go to the Azure portal and select the App Services. After running the service, click Get function URL > Copy. Include the URL as a query string in the URL. Then, paste it into the new browser tab. You will get the PDF document as follows. Example: https://htmltopdfazurefunctionblink.azurewebsites.net/api/Function1?code=aYCeymbJeHMGIwEEIuCIcNe….​&url=https://www.syncfusion.com A complete working sample can be downloaded from HtmlToPdf_AzureFunctions4.0.zip.Take a moment to peruse the documentation, where you can find converting HTML pages to PDF document along with respective customization options and features.Click here to explore the rich set of Syncfusion Essential® PDF features.An online sample link to convert HTML to PDF.ConclusionI hope you enjoyed learning about how to convert html to pdf in Azure portal.You can refer to our ASP.NET Core PDF Library's feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET Core PDF Library example to understand how to create and manipulate data.For current customers, you can check out our Document processing libraries from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls.If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!  
How to Convert Html String to WinForms PDF using C#?
The Syncfusion HTML to PDF Converter is a .NET library for converting webpages, SVG, MHTML, and  HTML to PDF using C#. It is reliable and accurate. The result preserves all graphics, texts, fonts and the layout of the original HTML document or webpage in  WinForms PDF. Using this library, you can convert HTML string to PDF document using C#. Steps to convert HTML string to PDF programmatically: Create a new C# Windows Forms application project. Install the Syncfusion.HtmlToPdfConverter.WinForms NuGet package as reference to your .NET Framework application from NuGet.org.  Include the following namespaces in the Form1.Designer.cs file. C# using Syncfusion.HtmlConverter; using Syncfusion.Pdf; using System.IO; Use the following code snippet to convert HTML string to PDF document. C# //Initialize HTML to PDF converter HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();   //Set HTML string and Base URL string htmlText = "<html><body Align='Left'></br><p> <font size='12'>Hello World</p></font> </body></html>"; string baseUrl = string.Empty;   //Convert HTML string to PDF PdfDocument document = htmlConverter.Convert(htmlText, baseUrl);   //Save and close the PDF document document.Save("Output.pdf"); document.Close(true);   //This will open the PDF file so, the result will be seen in default PDF viewer Process.Start("Output.pdf");   A complete working sample can be downloaded from HTMLStringtoPDF_Sample.zip. By executing the program, you will get the PDF document as follows. Take a moment to peruse the documentation, where you can find converting HTML pages to PDF document along with respective customization options and features. Refer here to explore the rich set of Syncfusion Essential PDF features. An online sample link for Converting HTML to PDF. Note:Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion license key in your application to use the components without trail message.ConclusionI hope you enjoyed learning about how to convert html string to WinForms PDF using C#.You can refer to our WinForms PDF featuretour page to know about its other groundbreaking feature representations and documentation, to understand how to create and manipulate data.For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or  feedback portal. We are always happy to assist you!  
How to set different margin settings in HTML when converting to PDF using C# in ASP.NET MVC?
Syncfusion® HTML to PDF for .NET is used to convert webpages, SVG, MHTML, and HTML to PDF. Using this library, you can set different page margins in HTML when converting to PDF document. Steps to set different margin settings in HTML to PDF conversion programmatically: Create a new ASP.NET MVC application project. Install the Syncfusion.HtmlToPdfConverter.AspNet.Mvc5 NuGet package as a reference to your .NET Framework applications from NuGet.org. A default controller with name HomeController.cs gets added on creation of ASP.NET MVC project. Include the following namespaces in that HomeController.cs file. C# using Syncfusion.Pdf; using Syncfusion.HtmlConverter; using System.Drawing; A default action method named Index will be presented in HomeController.cs. Right-click this action method and select Go To View, where you will be directed to its associated view page Index.cshtml. Add a new button in the Index.cshtml as follows.@using (Html.BeginForm("ConvertHtmlToPdf", "Home", FormMethod.Post)) {     <input type="submit" value="Convert" /> } Add a new action method named ConvertHtmlToPdf in HomeController.cs and include the following code snippet to set different margin settings in the conversion of HTML to PDF file and download it. C# //Input HTML URL to convert string url = Server.MapPath("~/Data/TableHTML.htm");   //Initialize HTML to PDF converter HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();   //Initialize Blink converter settings BlinkConverterSettings settings = new BlinkConverterSettings();   //Enable JavaScript settings.EnableJavaScript = true; settings.MediaType = MediaType.Print;   //Disable split images and text lines settings.SplitImages = false; settings.SplitTextLines = false;   //Set blink view port size settings.ViewPortSize = new Size(1200, 0);   //Set PDF page margin settings.Margin = new Syncfusion.Pdf.Graphics.PdfMargins { Top = 40, Left = 30, Right = 40, Bottom = 50 }; htmlConverter.ConverterSettings = settings;   //Convert URL to PDF document PdfDocument document = htmlConverter.Convert(url);   //Save and close the PDF document document.Save("Output.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save); document.Close(true); return null; A complete working sample can be downloaded from DifferentMarginSettingsHtmlToPDF.zip. By executing the program, you will get the PDF file as follows. Take a moment to peruse the documentation, where you can find converting HTML pages to PDF document along with respective customization options and features. Refer here to explore the rich set of Syncfusion Essential® PDF features. An online sample link for Converting HTML to PDF. Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion® license key in your application to use the components without trail message.     ConclusionI hope you enjoyed learning about how to set different margin settings in HTML when converting to PDF using C# in ASP.NET MVC.You can refer to our ASP.NET MVC PDF feature tour page to know about its other groundbreaking feature representations. You can also explore our documentation to understand how to present and manipulate data.For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other components.If you have any queries or require clarifications, please let us know in comments below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!
How to convert HTML to PDF in C#?
The Syncfusion HTML to PDF converter is a .NET library for converting web pages, SVG, MHTML and HTML to PDF using C#. It is reliable and accurate. The result preserves all graphics, images, texts, fonts, and the layout of the original HTML document or webpage. Convert HTML to PDF in C# In this tutorial, we will illustrate C# HTML to PDF conversion by using a simple console application. In addition, our HTML to PDF converter will work seamlessly in various platforms like Azure cloud or web apps, Azure functions, Amazon Web Service (AWS), Docker, WinForms, WPF, ASP.NET MVC, ASP.NET Core with Windows, Linux, and MacOS. Steps to convert HTML to PDF programmatically: Create a new C# console application project. Install the Syncfusion.HtmlToPdfConverter.WinForms NuGet package as reference to your .NET Framework application from NuGet.org. Include the following namespaces in the Program.cs file. C# using Syncfusion.Pdf; using Syncfusion.HtmlConverter;   Use the following code snippet to convert HTML (Website URL) to PDF document. C# //Initialize HTML to PDF converter HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(); //Convert HTML to PDF document PdfDocument document = htmlConverter.Convert("http://www.google.com/"); //Save the PDF document document.Save("HTMLToPDF.pdf"); //Close the document document.Close(true); //This will open the PDF file so, the result will be seen in default PDF viewer Process.Start("HTMLToPDF.pdf"); You can download the work sample from HTMLToPDFSample.Zip. By executing the program, you will get the PDF document as follows. Take a moment to peruse the documentation, where you can find converting HTML pages to PDF document along with respective customization options and features. Refer here to explore the rich set of Syncfusion Essential PDF features. An online sample link for Converting HTML to PDF. Note:Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion license key in your application to use the components without trail message.  
No articles found
No articles found
1 of 1 pages (18 items)