- [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 tạo ứng dụng dock windows giống Taskbar
- [C#] Chia sẻ source code sử dụng Object Listview trên Winform
- [VB.NET] Chia sẻ source code quản lý thu chi mô hình 3 lớp Winform
- [DATABASE] Xóa lịch sử danh sách đăng nhập tài khoản trên SMSS Sqlserver Management Studio
- [C#] Sử dụng FolderBrowserDialog Vista trên Winform
- [DEVEXPRESS] Chia sẻ tool Winform UI Templates Early Access Preview (EAP)
- [C#] Chia sẻ source code Spin Content (Trộn nội dung văn bản theo từ đồng nghĩa) trên Winform
- [VB.NET] Chia sẻ source code lịch âm dương và hẹn lịch nhắc việc
- [C#] Hướng dẫn đọc thông số thiết bị Thiết bị kiểm tra Pin (HIOKI BATTERY HiTESTER BT3562)
- [VB.NET] Hướng dẫn giải captcha sử dụng dịch vụ AZCaptcha API trên winform
- [C#] Hướng dẫn chứng thực đăng nhập ứng dụng bằng vân tay (Finger Print) trên máy tính
- [C#] Color Thief cách xuất màu sắc thiết kế từ hình ảnh
- [C#] Cách tạo bản quyền và cho phép dùng thử ứng dụng Winform
- [C#] Hướng dẫn sử dụng trình duyệt web Chrome convert HTML sang tập tin file PDF
- [C#] Kết nôi điện thoại Android, IOS với App Winform via Bluetooth
- [DATABASE] Cách query cộng trừ dồn dần trong Sqlserver
[Devexpress] Chèn Watermark Image Vào file PDF trong C# Full Source Code Google Drive
Hello anh em ! Mình là TONA, Xin giới thiệu phần mềm đóng dấu mộc đỏ vào file PDF, dấu tùy ý và vị trí cũng tùy ý luôn. Thực chất đây là cách mà mình có thể add một WaterMark vào một file PDF sẵn có. Mình chỉ làm demo, anh em tự phát triển thêm nhé !
[DevExpress] Add/insert a watermark to specific point in PDF file (multi pages)
Bài viết được thực hiện trên bộ thư viện của DevExpress phiên bản 19.2.5
- PDFViewer toolbox: Dùng để load và view PDF file.
- PdfDocumentProcessor: Dùng để build ra một file PDF mới
- PdfGraphics: Vẽ mọi thứ với khuôn khổ là một page của file PDF.
Trong bài này mình sẽ vẽ một con dấu vào góc trên bên phải của trang PDF nhé.
Full Source Code:
using DevExpress.Pdf;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Windows.Forms;
namespace AddImageToPDF
{
public partial class Form1 : DevExpress.XtraEditors.XtraForm
{
string urlFile;
public Form1()
{
InitializeComponent();
}
async void LoadPDFFile(string pdf_url)
{
using (WebClient client = new WebClient())
{
var data = await client.DownloadDataTaskAsync(new Uri(pdf_url));
pdfViewer1.DetachStreamAfterLoadComplete = true;
using (MemoryStream ms = new MemoryStream(data))
{
pdfViewer1.LoadDocument(ms);
urlFile = pdf_url;
}
}
}
void AddWatermarkImage(string fileName, string resultFileName)
{
using (PdfDocumentProcessor documentProcessor = new PdfDocumentProcessor())
{
documentProcessor.LoadDocument(fileName);
using (SolidBrush brush = new SolidBrush(Color.FromArgb(90, Color.Red)))
{
foreach (var page in documentProcessor.Document.Pages)
{
DrawImageToPage(page, documentProcessor, DateTime.Now.ToString("dd/MM/yyyy"), "TONA DINH");
}
}
documentProcessor.SaveDocument(resultFileName);
LoadPDFFile(resultFileName);
}
}
static void DrawImageToPage(DevExpress.Pdf.PdfPage page, PdfDocumentProcessor documentProcessor, string ngayduyet, string nguoiduyet)
{
using (PdfGraphics graphics = documentProcessor.CreateGraphics())
{
Image mark = Properties.Resources.mark;
int rt = page.Rotate;
using (Bitmap image = new Bitmap(mark, mark.Width / 9, mark.Height / 9))
{
PdfRectangle pdfRectangle = page.CropBox;
float cropBoxWidth = (float)pdfRectangle.Width;
float cropBoxHeight = (float)pdfRectangle.Height;
switch (page.Rotate)
{
case 90:
case 270:
cropBoxWidth = (float)pdfRectangle.Height;
cropBoxHeight = (float)pdfRectangle.Width;
break;
}
int markWidth = (int)cropBoxWidth - image.Width - 10;
Rectangle rec = new Rectangle(markWidth, 30, image.Width, image.Height);
graphics.DrawImage(SetImageOpacity(image, (float)0.2), rec);
string text = ngayduyet + "
" + nguoiduyet;
text = text.ToUpper();
string fontName = "Tahoma";
int fontSize = 14;
PdfStringFormat stringFormat = PdfStringFormat.GenericTypographic;
stringFormat.Alignment = PdfStringAlignment.Center;
stringFormat.LineAlignment = PdfStringAlignment.Near;
using (SolidBrush brush = new SolidBrush(Color.FromArgb(70, Color.Red)))
{
using (Font font = new Font(fontName, fontSize, FontStyle.Bold))
{
var watermarkSize = image.Width;
SizeF stringSize = graphics.MeasureString(text, font);
Single scale = Convert.ToSingle(watermarkSize / stringSize.Width);
using (Font actualFont = new Font(fontName, fontSize * scale, FontStyle.Bold))
{
RectangleF rect = new RectangleF(markWidth, image.Height + 25, stringSize.Width * scale, stringSize.Height * scale + 5);
graphics.DrawString(text, actualFont, brush, rect, stringFormat);
}
}
}
}
graphics.AddToPageForeground(page, 72, 72);
}
}
/// <summary>
/// method for changing the opacity of an image
/// </summary>
/// <param name="image">image to set opacity on</param>
/// <param name="opacity">percentage of opacity</param>
/// <returns></returns>
public static Image SetImageOpacity(Image image, float opacity = (float)0.2)
{
try
{
//create a Bitmap the size of the image provided
Bitmap bmp = new Bitmap(image.Width, image.Height);
//create a graphics object from the image
using (Graphics gfx = Graphics.FromImage(bmp))
{
//create a color matrix object
ColorMatrix matrix = new ColorMatrix();
//set the opacity
matrix.Matrix33 = opacity;
//create image attributes
ImageAttributes attributes = new ImageAttributes();
//set the color(opacity) of the image
attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
//now draw the image
gfx.DrawImage(image, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
}
return bmp;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
private void AddWatermark(string text, string fileName, string resultFileName)
{
using (PdfDocumentProcessor documentProcessor = new PdfDocumentProcessor())
{
string fontName = "Arial Black";
int fontSize = 12;
PdfStringFormat stringFormat = PdfStringFormat.GenericTypographic;
stringFormat.Alignment = PdfStringAlignment.Center;
stringFormat.LineAlignment = PdfStringAlignment.Center;
documentProcessor.LoadDocument(fileName);
using (SolidBrush brush = new SolidBrush(Color.FromArgb(90, Color.Red)))
{
using (Font font = new Font(fontName, fontSize))
{
foreach (var page in documentProcessor.Document.Pages)
{
var watermarkSize = page.CropBox.Width * 0.75;
using (PdfGraphics graphics = documentProcessor.CreateGraphics())
{
SizeF stringSize = graphics.MeasureString(text, font);
Single scale = Convert.ToSingle(watermarkSize / stringSize.Width);
graphics.TranslateTransform(Convert.ToSingle(page.CropBox.Width * 0.5), Convert.ToSingle(page.CropBox.Height * 0.5));
graphics.RotateTransform(-45);
graphics.TranslateTransform(Convert.ToSingle(-stringSize.Width * scale * 0.5), Convert.ToSingle(-stringSize.Height * scale * 0.5));
using (Font actualFont = new Font(fontName, fontSize * scale))
{
RectangleF rect = new RectangleF(0, 0, stringSize.Width * scale, stringSize.Height * scale);
graphics.DrawString(text, actualFont, brush, rect, stringFormat);
}
graphics.AddToPageForeground(page, 72, 72);
}
}
}
}
documentProcessor.SaveDocument(resultFileName);
}
}
public static Stream CopyStream(Stream input)
{
Stream output = new MemoryStream();
byte[] buffer = new byte[32768];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
return output;
}
private void btnSign_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
AddWatermarkImage(urlFile, urlFile);
}
private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Pdf Files|*.pdf";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
LoadPDFFile(openFileDialog.FileName);
}
}
}
}
Done !
Để lại còm men để cùng thảo luận và góp ý kiến nhé !!
HAPPY CODING !