/
Program.cs
63 lines (45 loc) · 2.06 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using System.Drawing;
using DevExpress.Pdf;
namespace ReplaceFormFieldWithImage {
class Program {
static void Main(string[] args) {
using (PdfDocumentProcessor processor = new PdfDocumentProcessor()) {
// Load a PDF document with AcroForm data.
processor.LoadDocument("..\\..\\InteractiveForm.pdf");
foreach (PdfInteractiveFormField field in processor.Document.AcroForm.Fields) {
if (field.Name == "Address") {
PdfRectangle cropBox = field.Widget.Page.CropBox;
PdfRectangle rect = field.Widget.Rect;
double x = rect.Left - cropBox.Left;
double y = cropBox.Top - rect.Bottom;
// Create graphics and draw an image.
using (PdfGraphics graphics = processor.CreateGraphics()) {
DrawImage(graphics, rect, x, y);
graphics.AddToPageForeground(processor.Document.Pages[0], 72, 72);
}
}
}
processor.RemoveFormField("Address");
processor.SaveDocument("..\\..\\Result.pdf");
}
}
static void DrawImage(PdfGraphics graphics, PdfRectangle rect, double x, double y) {
Bitmap image = new Bitmap("..\\..\\AddressFormField.png");
double aspectRatio = image.Width / image.Height;
double scaleX = image.Width / rect.Width;
double scaleY = image.Height / rect.Height;
double width;
double height;
if (scaleX < scaleY) {
width = rect.Width;
height = width / aspectRatio;
}
else {
height = rect.Height;
width = height * aspectRatio;
}
RectangleF imageRect = new RectangleF((float)x, (float)(y - height), (float)width, (float)height);
graphics.DrawImage(image, imageRect);
}
}
}