Creating pdf files with the PDF API (C# / netframework)
Note
This demo is available in your FlexCel installation at <FlexCel Install Folder>\samples\csharp\VS2022\netframework\10.API\A0.Creating Pdf Files With PDF API and also at https://github.com/tmssoftware/TMS-FlexCel.NET-demos/tree/master/csharp/VS2022/netframework/Modules/10.API/A0.Creating Pdf Files With PDF API
Overview
Even when FlexCel is not a full featured PDF package, it does have a basic PDF API that you can use to create PDF files from scratch.
Concepts
How to create a PDF file using FlexCel's internal PDF API. The API is very similar to GDI+, and allows you to use a PDF "Canvas" where you can draw things in. To use the API, you need to use the class PdfWriter
The PDF API on FlexCel is designed to support exporting Excel documents to PDF using FlexCelPdfExport. But you can use the same API FlexCelPdfExport uses to create your own PDF files with code.
Files
AssemblyInfo.cs
using System.Reflection;
using System.Runtime.CompilerServices;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly: AssemblyTitle("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("(c) 2002 - 2024 TMS Software")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("7.21.0.0")]
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the project output directory which is
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
[assembly: AssemblyKeyName("")]
Form1.cs
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using FlexCel.Core;
using FlexCel.Pdf;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Drawing.Drawing2D;
namespace CreatingPdfFilesWithPDFAPI
{
/// <summary>
/// Jow to create PDF files directly with FlexCel.
/// </summary>
public partial class mainForm: System.Windows.Forms.Form
{
public mainForm()
{
InitializeComponent();
}
private void button1_Click(object sender, System.EventArgs e)
{
if (saveFileDialog1.ShowDialog() != DialogResult.OK) return;
TUITextDecoration Underline = new TUITextDecoration(TUIUnderline.Single);
PdfWriter pdf = new PdfWriter();
using (FileStream file = new FileStream(saveFileDialog1.FileName, FileMode.Create))
{
pdf.Compress = true;
pdf.BeginDoc(file);
pdf.YAxisGrowsDown = true; //To keep it compatible with GDI+
using (TUIFont f = TUIFont.Create("times new roman", (float)22.5, TUIFontStyle.Italic))
{
using (TUIFont f2 = TUIFont.Create("Arial", (float)12, TUIFontStyle.Italic))
{
pdf.DrawString("This is the first line on a test of many lines.", f, Underline, Brushes.Navy, 100, 100);
pdf.DrawString("Some unicode: \u0e2a\u0e27\u0e31\u0e2a\u0e14\u0e35", f, Underline, Brushes.ForestGreen, 100, 200);
pdf.DrawString("More lines here!", f, Underline, Brushes.ForestGreen, 200, 300);
pdf.DrawString("And this is the last line.", f, Underline, Brushes.Black, 200, 400);
pdf.Properties.Author = "Adrian";
pdf.Properties.Title = "This is a test of FlexCel Api";
pdf.Properties.Keywords = "test\nflexcel\napi";
pdf.NewPage();
pdf.SaveState();
pdf.Rotate(200, 100, 45);
pdf.DrawString("Some rotated test", f, Underline, Brushes.Black, 200, 200);
pdf.RestoreState();
pdf.DrawString("Some NOT rotated text", f, Underline, Brushes.Black, 200, 200);
pdf.DrawString("Hello from FlexCel!", f2, Brushes.Black, 200, 50);
TPointF[] points = { new TPointF(200, 100), new TPointF(200, 50), new TPointF(500, 50), new TPointF(700, 100) };
pdf.DrawLines(Pens.DarkOrchid, points);
RectangleF Coords = new RectangleF(100, 300, 100, 100);
using (Brush Gradient = new LinearGradientBrush(Coords, Color.Red, Color.Blue, 0f))
{
pdf.DrawAndFillRectangle(Pens.Red, Gradient, 100, 300, 100, 100);
}
pdf.DrawRectangle(Pens.DarkSlateBlue, 100, 300, 50, 50);
pdf.DrawLine(Pens.Black, 100, 300, 200, 400);
string AssemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
using (Image Img = Image.FromFile(AssemblyPath + Path.DirectorySeparatorChar + ".." + Path.DirectorySeparatorChar + ".." + Path.DirectorySeparatorChar + "test.jpg"))
{
pdf.DrawImage(Img, new RectangleF(200, 300, 200, 150), null);
}
pdf.IntersectClipRegion(new RectangleF(100, 100, 50, 50));
pdf.FillRectangle(Brushes.DarkTurquoise, 100, 100, 100, 100);
pdf.EndDoc();
}
}
}
if (MessageBox.Show("Do you want to open the generated file?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
using (Process p = new Process())
{
p.StartInfo.FileName = saveFileDialog1.FileName;
p.StartInfo.UseShellExecute = true;
p.Start();
}
}
}
}
}
Form1.Designer.cs
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using FlexCel.Core;
using FlexCel.Pdf;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Drawing.Drawing2D;
namespace CreatingPdfFilesWithPDFAPI
{
public partial class mainForm: System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
private System.Windows.Forms.SaveFileDialog saveFileDialog1;
private System.Windows.Forms.Label label1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// button1
//
this.button1.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.button1.Location = new System.Drawing.Point(48, 160);
this.button1.Name = "button1";
this.button1.TabIndex = 0;
this.button1.Text = "GO!";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// saveFileDialog1
//
this.saveFileDialog1.Filter = "Pdf Files|*.pdf";
this.saveFileDialog1.RestoreDirectory = true;
//
// label1
//
this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.label1.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(255)), ((System.Byte)(192)));
this.label1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label1.Location = new System.Drawing.Point(16, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(144, 80);
this.label1.TabIndex = 1;
this.label1.Text = "A demo on how to create a PDF file with the PDF API.";
//
// mainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(168, 197);
this.Controls.Add(this.label1);
this.Controls.Add(this.button1);
this.Name = "mainForm";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
}
}
Program.cs
using System;
using System.Windows.Forms;
namespace CreatingPdfFilesWithPDFAPI
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new mainForm());
}
}
}