private void btn_toPDF_Click(object sender, EventArgs e)
{
ConvertToImg();
}
WebBrowser webBrowser = null;
/// <summary>
/// 拼接HTML代码
/// </summary>
/// <returns></returns>
public StringBuilder AppendStr()
{
StringBuilder str = new StringBuilder();
str.Append("<table border=\"1\" cellspacing=\"0\">");
str.Append("<tr>");
str.Append("<th>姓名</th>");
str.Append("<th>年龄</th>");
str.Append("<th>性别</th>");
str.Append("<th>职业</th>");
str.Append("<th>爱好</th>");
str.Append("<th>住址</th>");
str.Append("</tr>");
str.Append("<tr>");
str.Append("<td>张三</td>");
str.Append("<td>24</td>");
str.Append("<td>男</td>");
str.Append("<td>程序员</td>");
str.Append("<td>无</td>");
str.Append("<td>黄埔区</td>");
str.Append("</tr>");
str.Append("<tr>");
str.Append("<td>李四</td>");
str.Append("<td>23</td>");
str.Append("<td>女</td>");
str.Append("<td>程序员</td>");
str.Append("<td>肖战</td>");
str.Append("<td>天河区</td>");
str.Append("</tr>");
str.Append("</table>");
return str;
}
public void ConvertToImg()
{
StringBuilder html = AppendStr();
webBrowser = new WebBrowser();
//是否显式滚动条
webBrowser.ScrollBarsEnabled = false;
//加载 html
webBrowser.DocumentText =Convert.ToString(html);
//页面加载完成执行事件
webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
}
private void webBrowser_DocumentCompleted(object sender, EventArgs e)//这个就是当网页载入完毕后要进行的操作
{
//获取解析后HTML的大小
System.Drawing.Rectangle rectangle = webBrowser.Document.Body.ScrollRectangle;
int width = rectangle.Width;//rectangle.Width
int height = rectangle.Height;//rectangle.Height
//设置解析后HTML的可视区域
webBrowser.Width = width;
webBrowser.Height = height;
Bitmap bitmap = new Bitmap(width, height);
webBrowser.DrawToBitmap(bitmap, new System.Drawing.Rectangle(0, 0, width, height));
//设置图片文件保存路径和图片格式,格式可以自定义
string filePath = AppDomain.CurrentDomain.BaseDirectory + "../../../SaveFile/" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png";
bitmap.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
//创建PDF
FileStream fileStream = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "../../../SaveFile/" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".pdf", FileMode.Create);
byte[] result = CreatePDF(bitmap, width, height);
fileStream.Write(result, 0, result.Length);
fileStream.Close();
fileStream.Dispose();
}
public byte[] CreatePDF(Bitmap bitmap, int width, int height)
{
using (MemoryStream ms = new MemoryStream())
{
Document doc = new Document(new iTextSharp.text.Rectangle(0, 0, width, height), 3, 3, 3, 3); // 左右上下
PdfWriter writer = PdfWriter.GetInstance(doc, ms);
writer.CloseStream = false;
doc.Open();
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bitmap, System.Drawing.Imaging.ImageFormat.Png);
img.ScalePercent(100); // 放缩比例
doc.Add(img); // 添加图片对像
doc.Close();
return ms.ToArray();
}
}
原文地址:https://blog.csdn.net/slowlifes/article/details/72940116?locationNum=4&fps=1