- [C#] Hướng dẫn fix lỗi Visual Studio 2022 not Support Target Net Framework 4.5.2
- [C#] Giới thiệu thư viện Sunny UI thiết kế giao diện trên Winform
- [DATABASE] Hướng dẫn thêm và cập nhật Extended Property Column trong Table Sqlserver
- [DEVEXPRESS] Hướng dẫn sử dụng Vertical Gridview để hiển thị thông tin sản phẩm
- [C#] Hướng dẫn sử dụng Json Schema để Validate chuỗi string có phải json
- [C#] Hướng dẫn sử dụng công cụ Clean Code trên Visual Studio
- [C#] Hướng dẫn Drag and Drop File vào RichTextBox
- [C#] Hướng dẫn tạo hiệu ứng Karaoke Text Effect Winform
- [C#] Sử dụng thư viện ZedGraph vẽ biểu đồ Line, Bar, Pie trên Winform
- [DATABASE] Hướng dẫn sort sắp xếp địa chỉ IP trên sqlserver sử dụng hàm PARSENAME
- [C#] Theo dõi sử kiện process Start hay Stop trên Winform
- [ASP.NET] Chia sẻ source code chụp hình sử dụng camera trên website
- [C#] Chạy ứng dụng trên Virtual Desktop (màn hình ảo) Winform
- [C#] Mã hóa và giải mã Data Protection API trên winform
- [C#] Hướng dẫn tạo Gradient Background trên Winform
- [DATABASE] Hướng dẫn convert Epoch to DateTime trong sqlserver
- [DATABASE] Hướng dẫn sử dụng STRING_AGG và CONCAT_WS trong sqlserver 2017
- [C#] Hướng dẫn Copy With All Property in Class Object
- [DEVEXPRESS] Hướng dẫn load Json DataSource vào GridView
- [C#] Hướng dẫn tạo chữ ký trên winform Signature Pad
[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 !