create pdf file using Spire.Pdf or iTextSharp or PdfSharp

来源:http://www.cnblogs.com/geovindu/archive/2017/08/30/7452178.html
-Advertisement-
Play Games

Spire.Pdf: 註:pdf 顯示中文一定要設置相應的中文字體,其他外文類似。否則顯示為亂碼( 如果繁體的伺服器上生成的中文內容PDF文檔,在簡體操作系統保存或並傳給簡體系統上查看,會存在亂碼問題,這個需要考慮的) 安裝配置:PM> Install-Package Spire.PDF https ...


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/

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • .Net Core 2.0發佈了,API也越來越多。此時不用.Net Core,更待何時? 安裝.Net Core SDK 首先,我們當然要先裝.Net Core SDK,在這裡下載(https://www.microsoft.com/net/download/core)。我們可以看到Windows ...
  • 歐洲日期轉中文日期 歐洲大多數國家日期格式 24-12-1991 代表 dd-mm-yyyy 現在我想轉換成中文日期格式1991年12月24日 或者轉成國際標準格式日期 1991-12-24 yyyy-mm-dd格式 怎麼解決呢? 這裡我們可以通過正則表達式 輕鬆解決這個問題 通過這個例子我們可以舉 ...
  • 回到目錄 主要是通過vs2017+mysql.Data+Mysql.data.Entity+ef 來進行開始,當我們選擇數據模型生成實體時,可以會出現以下問題: http:// 解決辦法: 1、安裝mysql-connector-net-6.8.8.msi,地址,http://dev.mysql.c ...
  • 1.無法連接到網路 2.點擊安裝和更新無響 這兩種情況造成的原因都是由於被牆的原因,第一種情況有部分可以通過fq解決,第二種情況是我遇到過的 反正我全局也失敗 這裡給出一個我自己用過的解決方案 查看控制台日誌,中間有這麼一段: 將中間的網址粘貼到瀏覽器上面那個打開失敗 下麵那個可以正常打開,從裡面可 ...
  • 今天寫了個WCF介面,然後自測通過,和別人聯調時報 遠程伺服器返回錯誤: (413) Request Entity Too Large 錯誤!記得以前寫的時候也出現過這個錯誤,大致解決辦法是設置伺服器端的接收最大消息的限制改大點。但具體的配置節點及參數有點忘記了,網上搜了些資料改正並經過自測驗證後通 ...
  • http://www.wyjexplorer.cn/Post/2012/8/3/model-validation-in-aspnet-mvc3 ASP.NET MVC3中的Model是自驗證的,這是通過.NET4的System.ComponentModel.DataAnnotations命名空間完成 ...
  • 用戶登錄是一個非常常見的應用場景 .net core 2.0 的登錄方式發生了點變化,應該是屬於是良性的變化,變得更方便,更容易擴展。 打開項目中的Startup.cs文件,找到ConfigureServices方法,我們通常在這個方法裡面做依賴註入的相關配置。添加如下代碼: ...
  • 最近研究微信項目,套著web版微信協議做了一個客戶端,整體WPF項目MVVM架構及基本代碼參考於:http://www.cnblogs.com/ZXdeveloper/archive/2016/11/13/6058206.html 由於參考博主的項目沒有實現RichTextBox綁定圖片與後臺接收圖 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...