Table of Contents

Creating pdf files with the PDF API (VB.Net / netframework)

Note

This demo is available in your FlexCel installation at <FlexCel Install Folder>\samples\vb\VS2022\netframework\10.API\A0.Creating Pdf Files With PDF API and also at https:​//​github.​com/​tmssoftware/​TMS-​FlexCel.​NET-​demos/​tree/​master/​vb/​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.vb

Imports System.Reflection
Imports 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 - 2014 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("6.2.1.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.Designer.vb

Imports System.Collections
Imports System.ComponentModel
Imports FlexCel.Core
Imports FlexCel.Pdf
Imports System.IO
Imports System.Reflection
Imports System.Drawing.Drawing2D
Namespace CreatingPdfFilesWithPDFAPI
	Partial Public Class mainForm
		Inherits System.Windows.Forms.Form

		Private WithEvents button1 As System.Windows.Forms.Button
		Private saveFileDialog1 As System.Windows.Forms.SaveFileDialog
		Private label1 As System.Windows.Forms.Label
		''' <summary>
		''' Required designer variable.
		''' </summary>
		Private components As System.ComponentModel.Container = Nothing

		''' <summary>
		''' Clean up any resources being used.
		''' </summary>
		Protected Overrides Sub Dispose(ByVal disposing As Boolean)
			If disposing Then
				If components IsNot Nothing Then
					components.Dispose()
				End If
			End If
			MyBase.Dispose(disposing)
		End Sub

		#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 Sub InitializeComponent()
			Me.button1 = New System.Windows.Forms.Button()
			Me.saveFileDialog1 = New System.Windows.Forms.SaveFileDialog()
			Me.label1 = New System.Windows.Forms.Label()
			Me.SuspendLayout()
			' 
			' button1
			' 
			Me.button1.Anchor = System.Windows.Forms.AnchorStyles.Bottom
			Me.button1.Location = New System.Drawing.Point(48, 160)
			Me.button1.Name = "button1"
			Me.button1.TabIndex = 0
			Me.button1.Text = "GO!"
'			Me.button1.Click += New System.EventHandler(Me.button1_Click)
			' 
			' saveFileDialog1
			' 
			Me.saveFileDialog1.Filter = "Pdf Files|*.pdf"
			Me.saveFileDialog1.RestoreDirectory = True
			' 
			' label1
			' 
			Me.label1.Anchor = (CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) Or System.Windows.Forms.AnchorStyles.Left) Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles))
			Me.label1.BackColor = System.Drawing.Color.FromArgb((CByte(255)), (CByte(255)), (CByte(192)))
			Me.label1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
			Me.label1.Location = New System.Drawing.Point(16, 16)
			Me.label1.Name = "label1"
			Me.label1.Size = New System.Drawing.Size(144, 80)
			Me.label1.TabIndex = 1
			Me.label1.Text = "A demo on how to create a PDF file with the PDF API."
			' 
			' mainForm
			' 
			Me.AutoScaleDimensions = New System.Drawing.SizeF(6F, 13F)
			Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
			Me.ClientSize = New System.Drawing.Size(168, 197)
			Me.Controls.Add(Me.label1)
			Me.Controls.Add(Me.button1)
			Me.Name = "mainForm"
			Me.Text = "Form1"
			Me.ResumeLayout(False)

		End Sub
		#End Region
	End Class
End Namespace


Form1.vb

Imports System.Collections
Imports System.ComponentModel
Imports FlexCel.Core
Imports FlexCel.Pdf
Imports System.IO
Imports System.Reflection
Imports System.Drawing.Drawing2D

Namespace CreatingPdfFilesWithPDFAPI
	''' <summary>
	''' Jow to create PDF files directly with FlexCel.
	''' </summary>
	Partial Public Class mainForm
		Inherits System.Windows.Forms.Form

		Public Sub New()
			InitializeComponent()
		End Sub

		Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click
			If saveFileDialog1.ShowDialog() <> System.Windows.Forms.DialogResult.OK Then
				Return
			End If

            Dim Underline As TUITextDecoration = New TUITextDecoration(TUIUnderline.Single)

            Dim pdf As New PdfWriter()

			Using file As New FileStream(saveFileDialog1.FileName, FileMode.Create)
				pdf.Compress = True
				pdf.BeginDoc(file)
				pdf.YAxisGrowsDown = True 'To keep it compatible with GDI+
                Using f As TUIFont = TUIFont.Create("times new roman", CSng(22.5), TUIFontStyle.Italic)
                    Using f2 As TUIFont = TUIFont.Create("Arial", CSng(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: " & ChrW(&HE2A).ToString() & ChrW(&HE27).ToString() & ChrW(&HE31).ToString() & ChrW(&HE2A).ToString() & ChrW(&HE14).ToString() & ChrW(&HE35).ToString(), 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" & vbLf & "flexcel" & vbLf & "api"
                        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)

                        Dim points() As TPointF = { _
                            New TPointF(200, 100), _
                            New TPointF(200, 50), _
                            New TPointF(500, 50), _
                            New TPointF(700, 100) _
                        }
                        pdf.DrawLines(Pens.DarkOrchid, points)

                        Dim Coords As New RectangleF(100, 300, 100, 100)
                        Using Gradient As Brush = New LinearGradientBrush(Coords, Color.Red, Color.Blue, 0F)
                            pdf.DrawAndFillRectangle(Pens.Red, Gradient, 100, 300, 100, 100)
                        End Using
                        pdf.DrawRectangle(Pens.DarkSlateBlue, 100, 300, 50, 50)
                        pdf.DrawLine(Pens.Black, 100, 300, 200, 400)

                        Dim AssemblyPath As String = Path.GetDirectoryName(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location))
                        Using Img As Image = Image.FromFile(AssemblyPath & Path.DirectorySeparatorChar & ".." & Path.DirectorySeparatorChar & ".." & Path.DirectorySeparatorChar & "test.jpg")
                            pdf.DrawImage(Img, New RectangleF(200, 300, 200, 150), Nothing)
                        End Using
                        pdf.IntersectClipRegion(New RectangleF(100, 100, 50, 50))
                        pdf.FillRectangle(Brushes.DarkTurquoise, 100, 100, 100, 100)

                        pdf.EndDoc()
                    End Using
                End Using
            End Using
			If MessageBox.Show("Do you want to open the generated file?", "Confirm", MessageBoxButtons.YesNo) = System.Windows.Forms.DialogResult.Yes Then
				Process.Start(saveFileDialog1.FileName)
			End If

		End Sub
	End Class
End Namespace

Program.vb

Namespace CreatingPdfFilesWithPDFAPI
	Friend NotInheritable Class Program

		Private Sub New()
		End Sub

		''' <summary>
		''' The main entry point for the application.
		''' </summary>
		<STAThread> _
		Shared Sub Main()
			Application.EnableVisualStyles()
			Application.SetCompatibleTextRenderingDefault(False)
			Application.Run(New mainForm())
		End Sub
	End Class
End Namespace