- [C#] Di chuyển và thay đổi kích thước Control Winform khi ứng dụng đang chạy
- [VB.NET] Chia sẻ source tạo sắp xếp đội hình bóng đá Line-ups đội bóng
- [C#] Hướng dẫn chỉnh sửa Text của label trực tiếp trên winform
- [C#] Hướng dẫn custom TextBox giống Ultraviewer trên Winform
- [C#] Show Modal Winform like Bootstrap
- [DATABASE] Thứ tự thực hiện mệnh đề truy vấn SELECT trong Sqlserver
- [C#] Hướng dẫn viết addin Excel Lấy hình ảnh từ URL internet vào Excel
- [DATABASE] TSQL view max length all column data trên table Sqlserver
- [DEVEXPRESS] Hướng dẫn sử dụng MailMerge kèm Hình ảnh trên Winform
- [DATABASE] Hướng dẫn truy vấn xem kích thước lưu trữ của từng bảng ghi Table trên sqlserver
- [C#] Hướng dẫn Fake Date Time sử dụng thư viện Harmony
- [DATABASE] Phân biệt câu lệnh DDL và DML trong sqlserver
- [C#] Hướng dẫn convert file mã HTML sang file Pdf trên winform
- [DEVEXPRESS] Tạo các loại mã vạch Barcode trực tiếp trên Devexpress Barcode API
- [DEVEXPRESS] Hướng dẫn custom Simple button thành Progressbar
- [DATABASE] Tách số và chữ từ chuỗi - hàm tối ưu hóa tách số và chữ trong Sqlserver
- [C#] Tìm kiếm gần đúng Full Text Search sử dụng thư viện Lucene.NET
- [C#] Chia sẻ tài liệu, sdk và source code máy chấm công dòng máy ZKTeco
- [C#] Memory Cache là gì, và sử dụng trong ứng dụng Winform
- [DATABASE] Khóa chính Primary Key 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 !