- [C#] Hướng dẫn convert HTML code sang PDF File trên NetCore 7 Winform
- [C#] Hướng dẫn viết ứng dụng chat với Gemini AI Google Winform
- Hướng dẫn khóa file bằng nhiều process id, không cho xóa tập tin
- Hướng dẫn cách tạo Product Id cho ứng dụng phần mềm XXXXX-XXXXX-XXXXX-XXXXX
- [SQLSERVER] Hướng dẫn tạo script sql từ ứng dụng Sqlserver management Studio
- [C#] Hướng dẫn sử dụng thư viện AutoITx lấy id và password Ultraviewer trên winform
- [VB.NET] Hướng dẫn lấy thông tin tài khoản đăng nhập windows và khởi động lại ứng dụng ở chế độ Administrator
- [C#] Sử dụng thư viện Polly gửi lại request api khi request bị lỗi hay rớt mạng
- [DEVEXPRESS] Chia sẻ source code tạo báo cáo report in tem nhãn label trên C# winform
- [DEVEXPRESS] Hướng dẫn vẽ biểu đồ Bar Chart trên Winform
- [C#] Tạo form đăng nhập và đăng ký với hiệu ứng Sliding Animation Effect
- [C#] Hướng dẫn tạo thanh toán đơn hàng qua mã vạch VietQR sử dụng API PayOS hoàn toàn miễn phí
- [C#] Hướng dẫn ghi log ra RichTextBox giống Console trên Winform sử dụng thư viện Serilog
- [C#] Hướng dẫn cách tạo mã QR Code trên file Excel
- [VB.NET] Gởi tin nhắn và file đính kèm qua ứng dụng gởi tin nhắn Whats App
- [C#] Viết ứng dụng Auto Fill list Textbox from clipboard Winform
- [TOOL] Chia sẻ phần mềm thay đổi thông tin cấu hình máy tính
- [C#] Hướng dẫn Export dữ liệu ra file Microsoft Word Template
- [C#] Chia sẻ source code tool kiểm tra domain website
- [C#] Hướng dẫn tạo file PDF sử dụng thư viện QuestPDF
[C#] Hướng dẫn in hóa đơn Invoice từ Template HTML và xuất ra file PDF
Xin chào các bạn, bài viết hôm nay mình hướng dẫn các bạn cách xuất dữ liệu từ C# vào file template HTML trong lập trình C#, Winform.
[C#] Export data to HTML Template & Export PDF File
Ở bài này, mình sẽ sử dụng Template Engine Scriban để xuất dữ liệu, các bạn có thể tham khảo bài này ở web site của mình.
Video Demo ứng dụng Export Template C#:
- Đầu tiên, các bạn thiết kế 1 template invoice HTML, hoặc có thể tìm và download từ Internet về xong mình custom lại
Các bạn, thấy data mà chúng ta sẽ truyền vào được bọc bởi 2 dấu {{}}
Và dưới đây, là kết quả khi chúng ta đổ dữ liệu vào và xuất ra hóa đơn invoice template.
Và để xuất dữ liệu từ HTML sang PDF, bài viết mình sử dụng thư viện playwright để in.
Playwright là gì, thì bài viết tiếp theo, mình sẽ có bài viết về thư viện này.
Source code C#:
using Microsoft.Playwright;
using Scriban;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GeneratePDFFromTemplate
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public List<Product> GetProducts() {
var listProduct = new List<Product>();
var product5 = new Product()
{
Name = "Bí kiếp tán gái họ Nguyễn",
Price = 1000
};
var product1 = new Product()
{
Name = "Tự học C# trong 24h với Thảo Meo",
Price = 158000
};
var product2 = new Product()
{
Name = "Lập trình Mobile với Flutter 3.3 ",
Price = 255000
};
var product3 = new Product()
{
Name = "Cấu trúc dữ liệu & Thuật toán",
Price = 99000
};
var product4 = new Product()
{
Name = "Tự học OPP trong Java",
Price = 18000
};
listProduct.Add(product1);
listProduct.Add(product2);
listProduct.Add(product3);
listProduct.Add(product4);
listProduct.Add(product5);
return listProduct;
}
public dynamic GenerateDataDemo() {
var company = new
{
Name = txtCompany_name.Text,
Phone = txtCompanyPhone.Text,
Email = txtCompanyEmail.Text,
Location = txtCompanyLocation
};
var customer = new
{
Name = txtCustomerName.Text,
Mobile = txtCustomerMobile.Text,
Email = txtCustomerEmail.Text,
Address = txtCustomerAddress.Text
};
var fee = new
{
Total = GetProducts().Sum(x => x.Price).ToString("#,###"),
Tax = "10 %",
Transit = "35,000"
};
var data = new
{
Data = new {
Title = "Hóa đơn mua hàng",
Company = company,
Customer = customer,
NumInvoice = txtInvoiceNo.Text,
Products = GetProducts(),
Fee = fee,
Total = "2,585,000",
Date = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"),
Description = "Thanks for Shopping!"
}
};
return data;
}
private async void btnPrint_Click(object sender, EventArgs e)
{
var templateContent = File.ReadAllText("template_invoice.html");
var template = Template.Parse(templateContent);
var templateData = GenerateDataDemo();
var pageContent = template.Render(templateData);
File.WriteAllText("export.html", pageContent);
Process.Start("export.html");
var dataUrl = "data:text/html;base64," + Convert.ToBase64String(Encoding.UTF8.GetBytes(pageContent));
var playwright = await Playwright.CreateAsync();
var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
{
Headless = true,
});
var context = await browser.NewContextAsync();
var page = await context.NewPageAsync();
await page.GotoAsync(dataUrl, new PageGotoOptions { WaitUntil = WaitUntilState.NetworkIdle });
// Generate the PDF
var output = await page.PdfAsync(new PagePdfOptions
{
Format = "letter", // or "letter"
Landscape = true,
Margin = new Microsoft.Playwright.Margin() {Top = "0", Right ="0", Bottom = "0", Left = "0" },
Scale = 0.8f,
});
// Save the pdf to the disk
File.WriteAllBytes("invoice.pdf", output);
//File.WriteAllText("export.html", pageContent);
Process.Start("invoice.pdf");
}
}
public class Product
{
public string Name { get; set; }
public int Price { get; set; }
public string PriceAsString {
get {
return this.Price.ToString("#,###");
}
}
}
}
Thanks for watching!