以上是对PDF操作的相关类和方法的查看,由于此软件为商业软件,只能查看部分对外公开的代码,但是从可以查看到的代码就可以看出其内部实现的复杂度。
三.Spire.PDF for .NET实例:
由于本文主要讲解HTML页面转换为PDF文档,所以先提供一种GET请求HTML页面,以及一种获取页面图片的操作方法。接着介绍创建PDF文档、Text转化为PDF, XPS转换为PDF,Image转换为PDF等操作方法。
1.创建HTTP的GET请求,获取网页信息:
/// <summary> /// 指定路径发送GET请求 /// </summary> /// <param></param> /// <returns></returns> public static string HttpGet(string getUrl) { try { if (string.IsNullOrEmpty(getUrl)) throw new ArgumentNullException(getUrl); var request = WebRequest.Create(getUrl) as HttpWebRequest; if (request == null) return null; var cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "GET"; request.ContentType = "application/x-www-form-urlencoded"; var response = request.GetResponse() as HttpWebResponse; if (response != null) { var instream = response.GetResponseStream(); if (instream == null) throw new ArgumentNullException("getUrl"); string content; using (var sr = new StreamReader(instream, Encoding.UTF8)) { content = sr.ReadToEnd(); } return content; } } catch (Exception er) { throw new Exception(er.Message); } return null; }
2.取得HTML中所有图片的 URL:
/// <summary> /// 取得HTML中所有图片的 URL。 /// </summary> /// <param>HTML代码</param> /// <returns>图片的URL列表</returns> public static string HtmlCodeRequest(string url) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException(url); } try { //创建一个请求 var httprequst = (HttpWebRequest)WebRequest.Create(url); //不建立持久性链接 httprequst.KeepAlive = true; //设置请求的方法 httprequst.Method = "GET"; //设置标头值 httprequst.UserAgent = "User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705"; httprequst.Accept = "*/*"; httprequst.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.5"); httprequst.ServicePoint.Expect100Continue = false; httprequst.Timeout = 5000; //是否允许302 httprequst.AllowAutoRedirect = true; ServicePointManager.DefaultConnectionLimit = 30; //获取响应 var webRes = (HttpWebResponse)httprequst.GetResponse(); //获取响应的文本流 string content; using (var stream = webRes.GetResponseStream()) { using (var reader = new StreamReader(stream, Encoding.GetEncoding("utf-8"))) { content = reader.ReadToEnd(); } } //取消请求 httprequst.Abort(); //返回数据内容 return content; } catch (Exception ex) { throw new Exception(ex.Message); } }
3.创建PDF文档:
PdfDocument doc = new PdfDocument(); doc.LoadFromHTML(url, false, true, true); doc.Close();
以上没有将操作组装为一个方法,由于创建操作较为简单,所以不做详细介绍,url为网页路径地址。
HtmlConverter.Convert ("http://www.wikipedia.org/","HTMLtoPDF.pdf", //enable javascript true, //load timeout * 1000, //page size new SizeF(612, 792), //page margins new PdfMargins(0, 0));
4.Text转化为PDF:
public static void TextLayout() { //Create a pdf document. PdfDocument doc = new PdfDocument(); // Create one page PdfPageBase page = doc.Pages.Add(); float pageWidth = page.Canvas.ClientSize.Width; float y = 0; //page header PdfPen pen1 = new PdfPen(Color.LightGray, 1f); PdfBrush brush1 = new PdfSolidBrush(Color.LightGray); PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 8f, FontStyle.Italic)); PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Right); String text = "Demo of Spire.Pdf"; page.Canvas.DrawString(text, font1, brush1, pageWidth, y, format1); SizeF size = font1.MeasureString(text, format1); y = y + size.Height + 1; page.Canvas.DrawLine(pen1, 0, y, pageWidth, y); //title y = y + 5; PdfBrush brush2 = new PdfSolidBrush(Color.Black); PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold)); PdfStringFormat format2 = new PdfStringFormat(PdfTextAlignment.Center); format2.CharacterSpacing = 1f; text = "Summary of Science"; page.Canvas.DrawString(text, font2, brush2, pageWidth / 2, y, format2); size = font2.MeasureString(text, format2); y = y + size.Height + 6; //icon PdfImage image = PdfImage.FromFile(@"..\..\..\..\..\..\Data\Wikipedia_Science.png"); page.Canvas.DrawImage(image, new PointF(pageWidth - image.PhysicalDimension.Width, y)); float imageLeftSpace = pageWidth - image.PhysicalDimension.Width - 2; float imageBottom = image.PhysicalDimension.Height + y; //refenrence content PdfTrueTypeFont font3 = new PdfTrueTypeFont(new Font("Arial", 9f)); PdfStringFormat format3 = new PdfStringFormat(); format3.ParagraphIndent = font3.Size * 2; format3.MeasureTrailingSpaces = true; format3.LineSpacing = font3.Size * 1.5f; String text1 = "(All text and picture from "; String text2 = "Wikipedia"; String text3 = ", the free encyclopedia)"; page.Canvas.DrawString(text1, font3, brush2, 0, y, format3); size = font3.MeasureString(text1, format3); float x1 = size.Width; format3.ParagraphIndent = 0; PdfTrueTypeFont font4 = new PdfTrueTypeFont(new Font("Arial", 9f, FontStyle.Underline)); PdfBrush brush3 = PdfBrushes.Blue; page.Canvas.DrawString(text2, font4, brush3, x1, y, format3); size = font4.MeasureString(text2, format3); x1 = x1 + size.Width; page.Canvas.DrawString(text3, font3, brush2, x1, y, format3); y = y + size.Height; //content PdfStringFormat format4 = new PdfStringFormat(); text = System.IO.File.ReadAllText(@"..\..\..\..\..\..\Data\Summary_of_Science.txt"); PdfTrueTypeFont font5 = new PdfTrueTypeFont(new Font("Arial", 10f)); format4.LineSpacing = font5.Size * 1.5f; PdfStringLayouter textLayouter = new PdfStringLayouter(); float imageLeftBlockHeight = imageBottom - y; PdfStringLayoutResult result = textLayouter.Layout(text, font5, format4, new SizeF(imageLeftSpace, imageLeftBlockHeight)); if (result.ActualSize.Height < imageBottom - y) { imageLeftBlockHeight = imageLeftBlockHeight + result.LineHeight; result = textLayouter.Layout(text, font5, format4, new SizeF(imageLeftSpace, imageLeftBlockHeight)); } foreach (LineInfo line in result.Lines) { page.Canvas.DrawString(line.Text, font5, brush2, 0, y, format4); y = y + result.LineHeight; } PdfTextWidget textWidget = new PdfTextWidget(result.Remainder, font5, brush2); PdfTextLayout textLayout = new PdfTextLayout(); textLayout.Break = PdfLayoutBreakType.FitPage; textLayout.Layout = PdfLayoutType.Paginate; RectangleF bounds = new RectangleF(new PointF(0, y), page.Canvas.ClientSize); textWidget.StringFormat = format4; textWidget.Draw(page, bounds, textLayout); //Save pdf file. doc.SaveToFile("TextLayout.pdf"); doc.Close(); //Launching the Pdf file. PDFDocumentViewer("TextLayout.pdf"); }
5.XPS转换为PDF: