Hello,
Thanks for sharing your files via email.
I noticed that the mergefield in your template file is an image field, and in your expected result file, the corresponding location is also an image. Therefore, you can first use our Spire.PDF to convert the PDF file to an image, and then use our Spire.Doc to fill merge field with the image. You can refer to the following code to test.
- Code: Select all
static void Main(string[] args)
{
string imageName = "img.png";
string[] fieldNames = new string[] { "OrderHardCopy" };
string[] fieldValues = new string[] { imageName };
//Open a Word document
Document doc = new Document();
doc.LoadFromFile("example_template.docx");
//Open a pdf document
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("example.pdf");
Image image = pdf.SaveAsImage(0, Spire.Pdf.Graphics.PdfImageType.Bitmap, 500, 500);
SizeF pageSize = doc.Sections[0].PageSetup.PageSize;
////You can directly save the image in its original size
//image.Save(imageName);
//Or resize the image
resizeImage(image, new Size((int)pageSize.Width, image.Height)).Save(imageName);
//Fill field with image
doc.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MailMerge_MergeImageField);
doc.MailMerge.Execute(fieldNames, fieldValues);
//Save to file
doc.SaveToFile("result.pdf", Spire.Doc.FileFormat.PDF);
}
public static void MailMerge_MergeImageField(object sender, MergeImageFieldEventArgs field)
{
string filePath = field.ImageFileName;
if (!String.IsNullOrEmpty(filePath))
{
field.Image = Image.FromFile(filePath);
}
}
public static Image resizeImage(Image imgToResize, Size size)
{
//Get width and height of the image
int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
//Calculate the zoom ratio of the width
nPercentW = ((float)size.Width / (float)sourceWidth);
//Calculate the zoom ratio of the height
nPercentH = ((float)size.Height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
//Expected width
int destWidth = (int)(sourceWidth * nPercent);
//Expected height
int destHeight = (int)(sourceHeight * nPercent);
Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((System.Drawing.Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
//Draw image
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
g.Dispose();
return b;
}
Besides, please note that our Spire.Doc and Spire.PDF are two independent products. If you have further questions, just feel free to contact us.