Spire.Pdf:
注:pdf 显示中文一定要设置相应的中文字体,其他外文类似。否则显示为乱码
安装配置:PM> Install-Package Spire.PDF
https://stackoverflow.com/questions/5566186/print-pdf-in-c-sharp
class="brush:csharp;gutter:true;">/// <summary>
/// https://stackoverflow.com/questions/5566186/print-pdf-in-c-sharp
/// </summary>
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Create a pdf document.
PdfDocument doc = new PdfDocument();
//margin
PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
PdfMargins margin = new PdfMargins();
margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Bottom = margin.Top;
margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Right = margin.Left;
// Create one page
PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin);
Image img = Image.FromFile(@"data\bg.jpg");
page.BackgroundImage = img;
//Draw table
DrawPage(page);
//Save pdf file.
doc.SaveToFile("ImageWaterMark.pdf");
doc.Close();
//Launching the Pdf file.
// PDFDocumentViewer("ImageWaterMark.pdf");
//
PintDocumnet("ImageWaterMark.pdf");
}
/// <summary>
///
/// </summary>
/// <param name="page"></param>
private void DrawPage(PdfPageBase page)
{
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.jpg");
page.Canvas.DrawImage(image, new PointF(pageWidth - image.PhysicalDimension.Width, y));
float imageLeftSpace = pageWidth - image.PhysicalDimension.Width - 2;
float imageBottom = image.PhysicalDimension.Height + y;
//PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial Unicode MS", 11f), true);
//PdfCjkStandardFont font1 = new PdfCjkStandardFont(PdfCjkFontFamily.MonotypeSungLight, 11f);
//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",System.Text.Encoding.UTF8);
PdfTrueTypeFont font5 = new PdfTrueTypeFont(new Font("华文仿宋", 10f), true); // 华文仿宋 Arial Unicode MS true:是否unicode字符
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);
//result.Remainder = line.Text;
y = y + result.LineHeight;
}
PdfTextWidget textWidget = new PdfTextWidget("涂聚文编", font5, brush2);//result.Remainder
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);
}
/// <summary>
/// 浏览
/// </summary>
/// <param name="fileName"></param>
private void PDFDocumentViewer(string fileName)
{
try
{
System.Diagnostics.Process.Start(fileName);
}
catch { }
}
/// <summary>
/// 打印
/// </summary>
/// <param name="pdfPathAndFileName"></param>
private void PintDocumnet(string pdfPathAndFileName)
{
PdfDocument pdfdocument = new PdfDocument();
pdfdocument.LoadFromFile(pdfPathAndFileName);
pdfdocument.PrinterName = @"\\192.168.20.90\mpc4501";
pdfdocument.PrintDocument.PrinterSettings.Copies = 2;
pdfdocument.PrintDocument.Print();
pdfdocument.Dispose();
}
}
iTextSharp:
// public const string FONT = "c:/windows/fonts/arialbd.ttf"; //中文一定要是中文字体
// BaseFont bf = BaseFont.CreateFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
/// <summary>
/// Helper for DoCreateFromXmlStore(...).
/// Loads data from an XmlStore (or 'Plain Vanilla' XML) file into
/// the iTextSharp document.
/// NOTE: if you want to load data from some other source, clone this method and
/// write code specific to that data source, (i.e., replace the XmlStore-specific code)
/// but generally follow the pattern used here.
/// </summary>
/// <param name="document">the target iTextSharp document</param>
/// <param name="sXmlStoreFile">the source XmlStore (or 'Plain Vanilla' XML) file</param>
/// <returns>'true' if successful</returns>
private bool DoLoadDocument(Document document, string sXmlStoreFile)
{
bool bRet = false;
try
{
int numRecordsInXml = 0;
int numColumnsInXml = 0;
bool bExcludeIdColumn = true;
int BODY = 0; //index for font
int HDR = 1; //index for font
if (sXmlStoreFile.Length > 0)
{
//--- create an instance of XmlStore
VVX.XmlStore xstore = new XmlStore(sXmlStoreFile);
//--- load the data from the Xml file
numRecordsInXml = xstore.DoLoadRecords();
numColumnsInXml = xstore.Fields.Length;
if (numRecordsInXml > 0 && numColumnsInXml > 0)
{
int numColumnsInPDF = numColumnsInXml;
if (bExcludeIdColumn)
numColumnsInPDF = numColumnsInXml - 1;
// as we have data, we can create a PDFPTable
PdfPTable datatable = new PdfPTable(numColumnsInPDF);
// define the column headers, sizes, etc.
datatable.DefaultCell.Padding = 3; //in Points
//------------------------------------------------------------
// Set Column Widths
//------------------------------------------------------------
//--- set the relative width of each column
float[] columnWidthInPct = new float[numColumnsInPDF];
int col;
//--- see if we have width data for the Fields in XmlStore
float widthTotal = xstore.DoGetColumnWidthsTotal();
for (col = 0; col < numColumnsInPDF; col++)
{
if (widthTotal == 0f)
{
//--- equal widths (UGH!)
columnWidthInPct[col] = 100f / (float)numColumnsInPDF;
}
else
{
float widthCol = xstore.DoGetColumnWidth(col);
columnWidthInPct[col] = widthCol;
}
}
//--- set the total width of the table
if (mfWidthScaleFactor <= 0 || widthTotal == 0f)
datatable.WidthPercentage = 100; // percentage
else
datatable.WidthPercentage = widthTotal * mfWidthScaleFactor; // percentage
datatable.SetWidths(columnWidthInPct);
//获取所有打印机和安装字体
BaseFont bf = BaseFont.CreateFont(@"C:\Windows\Fonts\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
//------------------------------------------------------------
// Init fonts to be used
//------------------------------------------------------------
Font[] fonts = new Font[2];
string fontName = this.DoCvtToFontName(this.menBodyTypeFace);
float fontSize = this.mfBodyTypeSize;
int fontStyle = 0;
if (this.mbBodyTypeStyleBold)
fontStyle |= Font.BOLD;
if (this.mbBodyTypeStyleItalics)
fontStyle |= Font.ITALIC;
fonts[0] = FontFactory.GetFont(this.DoCvtToFontName(this.menBodyTypeFace),
this.mfBodyTypeSize,
this.DoCvtToStyle(this.mbBodyTypeStyleBold,
this.mbBodyTypeStyleItalics)
);
fonts[1] = FontFactory.GetFont(this.DoCvtToFontName(this.menHeaderTypeFace),
this.mfHeaderTypeSize,
this.DoCvtToStyle(this.mbHeaderTypeStyleBold,
this.mbHeaderTypeStyleItalics)
);
//------------------------------------------------------------
// Set Column Header Cell Attributes
//------------------------------------------------------------
datatable.DefaultCell.BorderWidth = 1;
datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
//------------------------------------------------------------
// Set Column Header Text
//------------------------------------------------------------
//int row = 0;
for (col = 0; col < numColumnsInXml; col++)
{
if (bExcludeIdColumn)
if (col == xstore.ColumnUID)
continue;
string sHdr = xstore.Fields[col].title;
Chunk chunk = new Chunk(sHdr, fonts[HDR]);
Phrase phrase = new Phrase(chunk);
datatable.AddCell(phrase);
}
datatable.HeaderRows = 1;
//------------------------------------------------------------
// Set the Data (i.e., rows)
//------------------------------------------------------------
//--- now add the rows of data
for (int row = 0; row < numRecordsInXml; row++)
{
// NOTE: if mbApplyAlternatingColors is 'true'
// the fill may cover any watermarks you want
if (mbApplyAlternatingColors && (row % 2 == 1))
{
datatable.DefaultCell.GrayFill = 0.9f; //very light gray
}
string[] bogusData = xstore.DoGetRecord(row);
for (col = 0; col < numColumnsInXml; col++)
{
if (bExcludeIdColumn)
if (col == xstore.ColumnUID)
continue;
string sText = bogusData[col];
Chunk chunk = new Chunk(sText, fonts[BODY]);
Phrase phrase = new Phrase(chunk);
datatable.AddCell(phrase);
}
// NOTE: if mbApplyAlternatingColors is 'true'
// the fill will cover any watermarks you want
if (mbApplyAlternatingColors && (row % 2 == 1))
{
datatable.DefaultCell.GrayFill = 1.0f; //white
}
}
//------------------------------------------------------------
// create an event handler instance
// This event handler does page-specific "drawing" and "painting"
// such as drawing the "title" in the header, the page number in the footer
// the watermark, and the gray background for the column header
//------------------------------------------------------------
VVX.XmlStoreEvent pageEvent = new XmlStoreEvent();
// configure it
this.DoConfigPageEventHandler(pageEvent);
// set the TableEvent to communicate with the event handler
datatable.TableEvent = pageEvent;
//------------------------------------------------------------
// Add the table to the PDF document
//------------------------------------------------------------
document.Add(datatable);
// let the caller know we successfully reached 'the end' of this
// request, i.e. loading the data into the iTextSharp 'document'
bRet = true;
}
}
}
catch (Exception e)
{
this.Message += e.StackTrace;
Debug.WriteLine(this.Message);
}
if (bRet == false)
{
document.Add(new Paragraph("Failed to load data from" + sXmlStoreFile));
}
return bRet;
}