How to Generate PDF Invoice from HTML Template for HTML to PDF API in C# with Web API

How to Create PDF Invoice from HTML Template for HTML to PDF API in C#: How-To Tutorial

Writing the code to generate a PDF invoice from an HTML template in C# can be done by developers of any level using Web API. Web API was made to help with HTML to PDF API in C#. Web API is a flexible Web API that includes a full set of functions from e-signature requests to data extraction, OCR, image recognition, PDF splitting, and PDF merging. Can also generate barcodes and read barcodes from images, scans, and PDFs.

C# code snippet like this for Web API works best when you need to quickly implement HTML to PDF API in your C# application. Follow the instruction and copy-paste the code for C# into your project’s code editor. Test C# sample code examples whether they respond to your needs and requirements for the project. Web API – free trial version is on available our website. Also, there are other code samples to help you with your C# application included in the trial version.

On-demand (REST Web API) version:
 Web API (on-demand version)

On-premise offline SDK for Windows:
 60 Day Free Trial (on-premise)


<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="12.0" DefaultTargets="Build" xmlns=""> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProjectGuid>{1E1C2C34-017E-4605-AE2B-55EA3313BE51}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>ByteScoutWebApiExample</RootNamespace> <AssemblyName>ByteScoutWebApiExample</AssemblyName> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PlatformTarget>AnyCPU</PlatformTarget> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PlatformTarget>AnyCPU</PlatformTarget> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Newtonsoft.Json, Version=, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL"> <HintPath>packages\Newtonsoft.Json.10.0.3\lib\net40\Newtonsoft.Json.dll</HintPath> <Private>True</Private> </Reference> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="System.Xml.Linq" /> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="Program.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> <Content Include="invoice_data.json"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </Content> <None Include="packages.config" /> </ItemGroup> <ItemGroup> <Content Include="invoice_template.html"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </Content> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>


Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2013 VisualStudioVersion = 12.0.40629.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ByteScoutWebApiExample", "ByteScoutWebApiExample.csproj", "{1E1C2C34-017E-4605-AE2B-55EA3313BE51}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {1E1C2C34-017E-4605-AE2B-55EA3313BE51}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1E1C2C34-017E-4605-AE2B-55EA3313BE51}.Debug|Any CPU.Build.0 = Debug|Any CPU {1E1C2C34-017E-4605-AE2B-55EA3313BE51}.Release|Any CPU.ActiveCfg = Release|Any CPU {1E1C2C34-017E-4605-AE2B-55EA3313BE51}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal


using System; using System.Collections.Generic; using System.IO; using System.Net; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace ByteScoutWebApiExample { class Program { // The authentication key (API Key). // Get your own by registering at const String API_KEY = "***********************************"; static void Main(string[] args) { // --TemplateID-- /* Please follow below steps to create your own HTML Template and get "templateId". 1. Add new html template in 2. Copy paste your html template code into this new template. Sample HTML templates can be found at "" 3. Save this new template 4. Copy it’s ID to clipboard 5. Now set ID of the template into “templateId” parameter */ // HTML template using built-in template // see var templateId = 2; // Data to fill the template string templateData = File.ReadAllText(@".\invoice_data.json"); // Destination PDF file name string destinationFile = @".\result.pdf"; // Create standard .NET web client instance WebClient webClient = new WebClient(); // Set API Key webClient.Headers.Add("x-api-key", API_KEY); webClient.Headers.Add("Content-Type", "application/json"); try { // URL for `HTML to PDF` API call string url = Uri.EscapeUriString(string.Format( "{0}", Path.GetFileName(destinationFile))); // Prepare requests params as JSON Dictionary parameters = new Dictionary(); parameters.Add("name", Path.GetFileName(destinationFile)); parameters.Add("templateId", templateId); parameters.Add("templateData", templateData); // Convert dictionary of params to JSON string jsonPayload = JsonConvert.SerializeObject(parameters); // Execute request string response = webClient.UploadString(url, jsonPayload); // Parse JSON response JObject json = JObject.Parse(response); if (json["error"].ToObject() == false) { // Get URL of generated PDF file string resultFileUrl = json["url"].ToString(); webClient.Headers.Remove("Content-Type"); // remove the header required for only the previous request // Download the PDF file webClient.DownloadFile(resultFileUrl, destinationFile); Console.WriteLine("Generated PDF document saved as \"{0}\" file.", destinationFile); } else { Console.WriteLine(json["message"].ToString()); } } catch (WebException e) { Console.WriteLine(e.ToString()); } webClient.Dispose(); Console.WriteLine(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } } }


{ "invoice_id": "1234567", "invoice_date": "April 30, 2016", "invoice_dateDue": "May 15, 2016", "paid": false, "issuer_name": "Acme Inc", "issuer_company": "Acme International", "issuer_address": "City, Street 3rd", "issuer_email": "", "issuer_website": "", "client_name": "Food Delivery Inc.", "client_company": "Food Delivery International", "client_address": "New York, Some Street, 42", "client_email": "", "items": [ { "name": "Setting up new web-site", "price": 250 }, { "name": "Website Content Addition", "price": 700 }, { "name": "Database Setup", "price": 200 }, { "name": "Record Digitalization", "price": 1800 }, { "name": "Cloud Storage", "price": 500 }, { "name": "Short Messages", "price": 35 }, { "name": "Search Engine Optimization", "price": 200 }, { "name": "Priority Support", "price": 75 }, { "name": "Configuring mail server and mailboxes", "price": 50 } ], "tax": 0.065, "discount": 0.01, "note": "Thank You For Your Business!" } }


<?xml version="1.0" encoding="utf-8"?> <packages> <package id="Newtonsoft.Json" version="10.0.3" targetFramework="net40" /> </packages>



Get 60 Day Free Trial

See also:


Get Your API Key

See also: