using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Shapes;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
using PdfSharp.Pdf;
namespace Project.PrintPDF
{
public partial class
PrintPDF : System.Web.UI.
Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Product> list=new List<Product>();
Product product=new Product();
list.Add(product);
string fileName = string.Format("products_{0}_{1}.pdf", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"), GenerateRandomDigitCode(4));
string filePath = string.Format("{0}files\\pdf\\{1}", HttpContext.Current.Request.PhysicalApplicationPath, fileName);
PrintProductsToPdf(list, filePath); //生成PDF
WriteResponsePdf(filePath, fileName); //下载PDF
}
public void PrintProductsToPdf(List<Product> productCollection, string filePath)
{
if (String.IsNullOrEmpty(filePath))
{
throw new ArgumentNullException("filePath");
}
Document doc = new Document();
Section section = doc.AddSection();
int productNumber = 1;
int prodCount = productCollection.Count;
foreach (var product in productCollection)
{
Paragraph p1 = section.AddParagraph(String.Format("{0}. {1}", productNumber, product.Name));
p1.Format.Font.Bold = true;
p1.Format.Font.Color = Colors.Black;
section.AddParagraph();
section.AddParagraph(StripTags(ConvertHtmlToPlainText(product.FullDescription)));
section.AddParagraph();
//加入图片
var pictures = product.ProductPicture;
if (pictures.Count > 0)
{
Table table = section.AddTable();
table.Borders.Visible = false;
table.AddColumn(Unit.FromCentimeter(10));
table.AddColumn(Unit.FromCentimeter(10));
Row row = table.AddRow();
for (int i = 0; i < pictures.Count; i++)
{
int cellNum = i % 2;
var pic = pictures[i];
if (pic != null && pic.PictureBinary != null && pic.PictureBinary.Length > 0)
{
row.Cells[cellNum].AddImage(product.PicturePath);
}
if (i != 0 && i % 2 == 0)
{
row = table.AddRow();
}
}
section.AddParagraph();
}
productNumber++;
if (productNumber <= prodCount)
{
section.AddPageBreak();
}
}
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
renderer.Document = doc;
renderer.RenderDocument();
renderer.PdfDocument.Save(filePath);
}
public void WriteResponsePdf(string filePath, string targetFileName)
{
if (!String.IsNullOrEmpty(filePath))
{
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Charset = "utf-8";
response.ContentType = "text/pdf";
response.AddHeader("content-disposition", string.Format("p_w_upload; filename={0}", targetFileName));
response.BinaryWrite(File.ReadAllBytes(filePath));
response.End();
}
}
public string GenerateRandomDigitCode(int length)
{
var random = new Random();
string str = string.Empty;
for (int i = 0; i < length; i++)
str = String.Concat(str, random.Next(10).ToString());
return str;
}
/// <summary>
/// Strips tags
/// </summary>
public string StripTags(string text)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
text = Regex.Replace(text, @"(>)(\r|\n)*(<)", "><");
text = Regex.Replace(text, "(<[^>]*>)([^<]*)", "$2");
text = Regex.Replace(text, "(&#x?[0-9]{2,4};|"|&| |<|>|€|©|®|‰|‡|†|‹|›|„|”|“|‚|’|‘|—|–|‏|‎|‍|‌| | | |˜|ˆ|Ÿ|š|Š)", "@");
return text;
}
/// <summary>
/// Converts HTML to plain text
/// </summary>
public string ConvertHtmlToPlainText(string text)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
text = text.Replace("<br>", "\n");
text = text.Replace("<br >", "\n");
text = text.Replace("<br />", "\n");
text = text.Replace(" ", "\t");
text = text.Replace(" ", " ");
return text;
}
}
public
class
Product
{
public Product()
{ }
/// <summary>
/// Gets or sets the name
/// </summary>
public string Name
{
get {
return @"Camera - Canon EOS";
}
}
/// <summary>
/// Gets or sets the full description
/// </summary>
public string FullDescription
{
get {
return @"<p>Jazz up any outfit with this classic diamond tennis bracelet. This piece has one full carat of diamonds uniquely set in brilliant 10 karat white gold.</p>";
}
}
public IList<Picture> ProductPicture
{
get
{
List<Picture> list = new List<Picture>();
Picture p = new Picture();
p.PictureBinary = System.IO.File.ReadAllBytes(PicturePath);
list.Add(p);
return list;
}
}
public string PicturePath
{
get {
return HttpContext.Current.Server.MapPath("pro201010107492.jpg");
}
}
}
public class
Picture
{
public Picture() { }
public byte[] PictureBinary { get; set; }
}
}
附:pdfsharp×××地址---
http://sourceforge.net/projects/pdfsharp/
转载于:https://blog.51cto.com/xiaoyaosr/447355