gpt4 book ai didi

replace - 如何使用 Novacode Docx 替换 word 文档中的图像

转载 作者:行者123 更新时间:2023-12-02 03:11:04 25 4
gpt4 key购买 nike

我想使用 Novacode Docx 替换 word 文档中的图像,但我只知道通过此代码插入

var gDoc = DocX.Load(@"MauPhieuNhapCBCC.docx");
using (MemoryStream ms = new MemoryStream())
{
System.Drawing.Image myImg = System.Drawing.Image.FromFile(@"img.jpg");

myImg.Save(ms, myImg.RawFormat); // Save your picture in a memory stream.
ms.Seek(0, SeekOrigin.Begin);

Image img = gDoc.AddImage(ms); // Create image.
Picture pic1 = img.CreatePicture();
// Create picture.
var abc = gDoc.Paragraphs.FirstOrDefault(g => g.Pictures.Count > 0);
abc.Alignment = Alignment.right;
abc.InsertPicture(pic1,29).Position(0.3); // Insert picture into paragraph.
}
gDoc.SaveAs("Exported.docx");

如何在特殊位置无法替换或插入?

最佳答案

你可以这样做,这可能不是理想的方式,但它工作正常:

var gDoc = DocX.Load(@"MauPhieuNhapCBCC.docx");
for (int f = 0; f < gDoc.Images.Count; f++) //Loop through the images of the document
{
Novacode.Image imo = gDoc.Images[f]; //Get image of the docuemnt
if (imo.Id == "imageIdInDocument") //Check the id
{
using (SD.Image newImg = SD.Image.FromFile("newImagePath")) //Load the new image for replacement
{
SD.Bitmap bMa = new SD.Bitmap(imo.GetStream(FileMode.Open, FileAccess.ReadWrite));
SD.Graphics graf = SD.Graphics.FromImage(bMa);
graf.Clear(SD.Color.White); //Set the image of the document all white

//Below we insert our new image over the one in the document
//We might need to change the image size to fit the area of our existing image
//If that were the case we give a function to resize images
SD.Image newResizeImg = meths.ResizeImage(newImg, newWidth, newHeight);

//Below we set the point(0, 0) to overlap the new image from the top left corner
graf.DrawImage(newResizeImg, new SD.Rectangle(new SD.Point(0, 0), newResizeImg.Size),
new SD.Rectangle(new SD.Point(), newResizeImg.Size), SD.GraphicsUnit.Pixel);
bMa.Save(imo.GetStream(FileMode.Create, FileAccess.Write), SD.Imaging.ImageFormat.Jpeg);
}

}
}

这里是调整图片大小的函数:

public SD.Image ResizeImage(SD.Image img, int newWidth, int newHeight)
{
if (img.Width < newWidth && img.Height < newHeight) return img;
using (img)
{
SD.Bitmap cpy = new SD.Bitmap(newWidth, newHeight, SD.Imaging.PixelFormat.Format32bppArgb);
using (SD.Graphics gr = SD.Graphics.FromImage(cpy))
{
gr.Clear(SD.Color.Transparent);
gr.InterpolationMode = SD.Drawing2D.InterpolationMode.HighQualityBicubic;
gr.DrawImage(img, new SD.Rectangle(0, 0, newWidth, newHeight), new SD.Rectangle(0, 0, img.Width, img.Height), SD.GraphicsUnit.Pixel);
}
return cpy;
}
}

我们基本上做的是获取文档的图像,将其涂成白色,然后将新图像设置在现有图像中,大小相同或更小。希望这对某人有帮助。

关于replace - 如何使用 Novacode Docx 替换 word 文档中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40039745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com