- [DEVEXPRESS] Hướng dẫn bật tính năng Scroll Pixcel in Touch trên GridView
- [DEVEXPRESS] Hướng dẫn sử dụng TileBar viết ứng dụng duyệt hình ảnh Winform
- [DEVEXPRESS] Tô màu border TextEdit trên Winform
- [C#] Lấy dữ liệu từ Console Write hiển thị lên textbox Winform
- [C#] Hiển thị Progress bar trên Window Console
- [C#] Di chuyển control Runtime và lưu layout trên winform
- [SQLSERVER] Sử dụng hàm NULL IF
- [C#] Chia sẽ source code mã đi tuần bằng giao diện Winform
- [C#] Flash Window in Taskbar Winform
- Download và Giải nén tập tin File sử dụng Powershell
- [C#] Hướng dẫn cách lấy thông tin đăng nhập tài khoản và mật khẩu web browser trên windows
- [VB.NET] CRUD Thêm xóa sửa tìm kiếm Realtime FireBase
- [C#] Hiển thị thông báo Toast Message trong lập trình Winform
- [C#] Cấu hình định dạng ngày tháng, thời gian trên Windows cho ứng dụng Winform
- [C#] Rút gọn đường dẫn link url với TinyURL API
- [C#] Hướng dẫn cách bo tròn winform with Radius
- [C#] Chia sẽ class BackGroundOverlay Show Modal cho Winform
- [C#] Hướng dẫn Flip Image Winform
- [C#] Invoke là gì? cách sử dụng phương thức Invoke()
- [C#] Hướng dẫn chia sẽ file, folder từ ứng dụng sang Zalo Chat
[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 !