create pdf file using Spire.Pdf or iTextSharp or PdfSharp

Spire.Pdf:

注:pdf 显示中文一定要设置相应的中文字体,其他外文类似。否则显示为乱码( 如果繁体的服务器上生成的中文内容PDF文档,在简体操作系统保存或并传给简体系统上查看,会存在乱码问题,这个需要考虑的)

安装配置:PM> Install-Package Spire.PDF

https://sourceforge.net/projects/freespirepdffornet/

https://code.msdn.microsoft.com/windowsapps/Using-SpirePDF-In-AspNet-425e5d56

https://pdfapi.codeplex.com/

http://freepdf.codeplex.com/

https://stackoverflow.com/questions/5566186/print-pdf-in-c-sharp

/// <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();
}

}

 web:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Spire.Pdf;
using Spire.License.V1_2;
using Spire.Pdf.Graphics;
using Spire.Pdf.Tables;
using System.Drawing;
using System.IO;

namespace SpirePDFDemo
{

    /// <summary>
    /// 
    /// </summary>
    public partial class _Default : System.Web.UI.Page
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {



        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        private void DrawPage(PdfPageBase page)
        {

            string local = Server.MapPath(@"~/");

            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(local+@"\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(local + @"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();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            string local = Server.MapPath(@"~/");
            //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);

            System.Drawing.Image img = System.Drawing.Image.FromFile(local+@"data\bg.jpg");
            page.BackgroundImage = img;

            //Draw table
            DrawPage(page);

            //Save pdf file.
            doc.SaveToFile(local + "data\\ImageWaterMark.pdf");
            doc.Close();

            //Launching the Pdf file.
            // PDFDocumentViewer(local + "data\\ImageWaterMark.pdf");
            //
            PintDocumnet(local + "data\\ImageWaterMark.pdf");
        }
    }
}

  

 

 iTextSharp:

https://github.com/itext/itextsharp

https://github.com/itext

https://github.com/itext/itext7-dotnet/releases/tag/7.0.4

// 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;
        }

 PdfSharp:

http://pdfsharp.codeplex.com/

https://github.com/empira/PDFsharp/

https://sourceforge.net/projects/pdfsharp/

https://www.nuget.org/packages/PdfSharp

    /// <summary>
    /// 
    /// </summary>
    public partial class Form1 : Form
    {
        /// <summary>
        /// Renders the content of the page.
        /// </summary>
        public void Render(XGraphics gfx)
        {

            XRect rect;
            XPen pen;
            double x = 50, y = 100;
            XFont fontH1 = new XFont("华文仿宋", 18, XFontStyle.Bold);//华文仿宋
            XFont font = new XFont("华文仿宋", 12);//Arial  必须是中文字体
            XFont fontItalic = new XFont("Arial Unicode MS", 12, XFontStyle.BoldItalic);
            double ls = 14;// font.GetHeight(gfx);   //GetHeight

            // Draw some text
            gfx.DrawString("Create PDF on the fly with PDFsharp  中国文",
                fontH1, XBrushes.Black, x, x);
            gfx.DrawString("With PDFsharp you can use the same code to draw graphic, " +
                "text and images on different targets.涂聚文,捷为工作室", font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("The object used for drawing is the XGraphics object.",
                font, XBrushes.Black, x, y);
            y += 2 * ls;

            // Draw an arc
            pen = new XPen(XColors.Red, 4);
            pen.DashStyle = XDashStyle.Dash;
            gfx.DrawArc(pen, x + 20, y, 100, 60, 150, 120);

            // Draw a star           

            gfx.TranslateTransform(x + 140, y + 30);
            for (int idx = 0; idx < 360; idx += 10)
            {
                gfx.RotateTransform(10);
                gfx.DrawLine(XPens.DarkGreen, 0, 0, 30, 0);
            }

            XGraphicsState gs = gfx.Save();
            gfx.Restore(gs);


            // Draw a rounded rectangle
            rect = new XRect(x + 230, y, 100, 60);
            pen = new XPen(XColors.DarkBlue, 2.5);
            XColor color1 = XColor.FromKnownColor(XKnownColor.DarkBlue);//  //XColor.FromKnownColor(KnownColor.DarkBlue);
            XColor color2 = XColors.Red;
            XLinearGradientBrush lbrush = new XLinearGradientBrush(rect, color1, color2,
              XLinearGradientMode.Vertical);
            gfx.DrawRoundedRectangle(pen, lbrush, rect, new XSize(10, 10));

            // Draw a pie
            pen = new XPen(XColors.DarkOrange, 1.5);
            pen.DashStyle = XDashStyle.Dot;
            gfx.DrawPie(pen, XBrushes.Blue, x + 360, y, 100, 60, -130, 135);
            //没有自动分行
            // Draw some more text
            y += 60 + 2 * ls;
            gfx.DrawString("With XGraphics you can draw on a PDF page as well as " +
                "on any System.Drawing.Graphics object.", font, XBrushes.Black, x, y);
            y += ls * 1.1;
            gfx.DrawString("Use the same code to", font, XBrushes.Black, x, y);
            x += 10;
            y += ls * 1.1;
            gfx.DrawString("• draw on a newly created PDF page", font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("• draw above or beneath of the content of an existing PDF page",
                font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("• draw in a window", font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("• draw on a printer", font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("• draw in a bitmap image", font, XBrushes.Black, x, y);
            x -= 10;
            y += ls * 1.1;
            gfx.DrawString("You can also import an existing PDF page and use it like " +
                "an image, e.g. draw it on another PDF page.", font, XBrushes.Black, x, y);
            y += ls * 1.1 * 2;
            gfx.DrawString("Imported PDF pages are neither drawn nor printed; create a " +
                "PDF file to see or print them!", fontItalic, XBrushes.Firebrick, x, y);
            y += ls * 1.1;
            gfx.DrawString("Below this text is a PDF form that will be visible when " +
                "viewed or printed with a PDF viewer.", fontItalic, XBrushes.Firebrick, x, y);
            y += ls * 1.1;
            //XGraphicsState state = gfx.Save();
            //gfx.Restore(state);
            XRect rcImage = new XRect(100, y, 100, 100 * Math.Sqrt(2));
            gfx.DrawRectangle(XBrushes.Snow, rcImage);
            gfx.DrawImage(XPdfForm.FromFile("bicycle.pdf"), rcImage);
            
            XGraphicsState states = gfx.Save();
            gfx.Restore(states);
           

        }
        /// <summary>
        /// 
        /// </summary>
        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            // Create a new PDF document
            PdfSharp.Pdf.PdfDocument document = new PdfSharp.Pdf.PdfDocument();

            // Create an empty page
            PdfPage page = document.AddPage();
            //page.Contents.CreateSingleContent().Stream.UnfilteredValue;

            // Get an XGraphics object for drawing
            XGraphics gfx = XGraphics.FromPdfPage(page);
            Render(gfx);
           SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter = "pdf files (*.pdf)|*.pdf|All files (*.*)|*.*";
            saveFileDialog1.FilterIndex = 1;
            saveFileDialog1.RestoreDirectory = true;

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                document.Save(saveFileDialog1.FileName);
                Process.Start(saveFileDialog1.FileName);
            }
        }

  https://github.com/mozilla/pdf.js/

 

转载于:https://www.cnblogs.com/geovindu/p/7452178.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值