#region 创建 Word 文档
string templatePath = Server.MapPath("template.docx");
// 只创建一个Document(关键优化)
Document doc = new Document(templatePath);
//清空模板内容(如果模板只是占位用)
doc.RemoveAllChildren();
//用Builder写入(核心:避免AppendDocument)
DocumentBuilder builder = new DocumentBuilder(doc);
#endregion
#region 数据
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
var row = ds.Tables[0].Rows[i];
// 获取图片路径
string xys = getimg1(row["xys"].ToString(), obj);
string[] pic = Fun.splitstr(xys, "、");
if (string.IsNullOrEmpty(pic[0]))
continue;
if (pic[0] == "/templates/default/images/icon/pdf.gif")
continue;
if (Fun.GetStrRight(pic[0], 1) == ".")
pic[0] = pic[0] + "jpg";
string imagePath = Server.MapPath(pic[0]);
// ===== 1. 标题 =====
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Size = 16;
builder.Font.Bold = true;
builder.Writeln(row["hzqymc"].ToString());
builder.Font.ClearFormatting();
builder.ParagraphFormat.ClearFormatting();
// ===== 2. 图片(限制尺寸避免OOM)=====
try
{
using (var img = System.Drawing.Image.FromFile(imagePath))
{
int width = 800;
int height = (int)(img.Height * (800.0 / img.Width));
using (var bmp = new Bitmap(img, new Size(width, height)))
{
string temp = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".jpg");
bmp.Save(temp, System.Drawing.Imaging.ImageFormat.Jpeg);
builder.InsertImage(temp, 0, 600);
File.Delete(temp);
}
}
}
catch
{
FileObj.FileAdd(Server.MapPath("1.txt"),
row["hzqymc"] + "----" + pic[0] + "\r\n");
}
// ===== 3. 分页 =====
if (i < ds.Tables[0].Rows.Count - 1)
{
builder.InsertBreak(BreakType.PageBreak);
}
}
}
#endregion
#region 下载
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
Response.AddHeader("Content-Disposition", "attachment; filename=协议书.docx");
using (var ms = new MemoryStream())
{
doc.Save(ms, SaveFormat.Docx);
ms.Position = 0;
byte[] buffer = new byte[81920]; // 80KB 缓冲(推荐)
int bytesRead;
while ((bytesRead = ms.Read(buffer, 0, buffer.Length)) > 0)
{
Response.OutputStream.Write(buffer, 0, bytesRead);
}
Response.Flush();
Response.End();
}
#endregion