How to Create Digital Certificate in PDF – C#/Vb.NET

In order to verify our own identify or distinguish others’ identify online, Certificate Authority published digital certificate, which includes a public key, information key owner. Digital certificate plays a very important role when delivering information online. It can protect security of personal account, password and other important information when we trade with others online. In this post, I will show the method about how to create digital certificate in a PDF document with C# and VB.NET.

In my example, I prepare a certificate, which is not an official certificate but a simple one for example.

Now, let’s follow the steps to create PDF digital certificate.

At the beginning, I add Spire.PDF dll file as reference because I will use this third-party component in my method.

  1. Create a PDF document and add one page. Because I just want to show an example, so I don’t draw any contents on this blank page.
  2. Create certificate and signature. Firstly, declare a string pfxPath and assign certificate as value to it. Secondly, create certificate. It should include two parameters, pfxPath and a password. Thirdly, add signature. There are four parameters, PDF document, page, certificate and signature name.  Finally, set other information, including contact information, document permission.
  3. Save and launch file.

Main Coding:

C#

using System;

using Spire.Pdf;

using Spire.Pdf.Security;

namespace DigitalCertificate

{

    class Certificate

    {

        static void Main(string[] args)

        {

            //Create Document and Add Page

            PdfNewDocument doc = new PdfNewDocument();

            PdfPageBase page = doc.Pages.Add();

            //Create Certificate and Signature

            String pfxPath = @”D:\work\My Documents\Certificate.pfx”;

            PdfCertificate cert = new PdfCertificate(pfxPath, “e-iceblue”);

            PdfSignature signature = new PdfSignature(doc, page, cert, “Certificate”);

            signature.ContactInfo = “JaneWDasiy”;

            signature.Certificated = true;

            signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill;

            //Save and Launch

            doc.Save(“DigitalCertificate.pdf”);

            doc.Close();

            System.Diagnostics.Process.Start(“DigitalCertificate.pdf”);

        }

    }

}

VB.NET

Imports System

Imports Spire.Pdf

Imports Spire.Pdf.Security

Namespace DigitalCertificate

       Friend Class Certificate

              Shared Sub Main(ByVal args() As String)

                     ‘Create Document and Add Page

                     Dim doc As New PdfNewDocument()

                     Dim page As PdfPageBase = doc.Pages.Add()

                     ‘Create Certificate and Signature

                     Dim pfxPath As String = “D:\work\My Documents\Certificate.pfx”

                     Dim cert As New PdfCertificate(pfxPath, “e-iceblue”)

                     Dim signature As New PdfSignature(doc, page, cert, “Certificate”)

                     signature.ContactInfo = “JaneWDasiy”

                     signature.Certificated = True

                     signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill

                     ‘Save and Launch

                     doc.Save(“DigitalCertificate.pdf”)

                     doc.Close()

                     System.Diagnostics.Process.Start(“DigitalCertificate.pdf”)

              End Sub

       End Class

End Namespace

Result Shown by Following:

__________________________________________________________________

Click Here to Learn more about Spire.PDF

Click Here to Download Spire.PDF

How to Set Graphics Overlay in PDF – C#/VB.NET

In order to have a wonderful and appealed appearance, people use some special effects on images, which are often used in advertisements. Also, we can apply images with special effects to our documents. In this post, I will show the method about how to overlay one image on another one in PDF by using C#/VB.NET.

Actually, graphic overlay in PDF doesn’t mean that the upper image will cover lower one, but the lower can be regarded as background image with certain transparency or watermark. In my example, I prepare two PDF documents. Each of them has one page. What I will do is to overlay image in document 2 on image in document 1.

                                                G.JPG in Doc 2                                                                         F.JPG in Doc 1

Steps:

Before starting with steps, I must notice that I use Spire.PDF in this example so that I add its dll file as reference in my project.

  1. Load document 1 and document 2 from my computer.
  2. Create a template based on document 1 pages.
  3. Use for loop to overlay pages in document 2 on document 1. Although document 2 has only one page, we should suppose that there are several pages in this document. In this for loop, I set transparency and draw template. In SetTransparency method, I pass three parameters, pen, brush and blend mood, while, in DrawTemplate method, there are two parameters, template which I have created in step 2 and location.
  4. Save and Launch file.

Main Coding:

C#

using System;

using System.Drawing;

using Spire.Pdf;

using Spire.Pdf.Graphics;

namespace GraphicsOverlay

{

    class overlay

    {

        static void Main(string[] args)

        {

            //Load Document

            PdfDocument doc1 = new PdfDocument();

            doc1.LoadFromFile(@”D:\work\My Documents\F.pdf”);

            PdfDocument doc2 = new PdfDocument();

            doc2.LoadFromFile(@”D:\work\My Documents\G.pdf”);

            //Create Template

            PdfTemplate template = doc1.Pages[0].CreateTemplate();

            foreach (PdfPageBase page in doc2.Pages)

            {

                page.Canvas.SetTransparency(0.55f, 0.55f, PdfBlendMode.Overlay);

                page.Canvas.DrawTemplate(template, PointF.Empty);

            }

            //Save

            doc2.SaveToFile(“Overlay.pdf”);

            doc1.Close();

            doc2.Close();

            //Launch

            System.Diagnostics.Process.Start(“Overlay.pdf”);

        }

    }

}

VB.NET

Imports System

Imports System.Drawing

Imports Spire.Pdf

Imports Spire.Pdf.Graphics

NamespaceGraphicsOverlay

       Friend Class overlay

              Shared Sub Main(ByVal args() As String)

                     ‘Load Document

                     Dim doc1 As New PdfDocument()

                     doc1.LoadFromFile(“D:\work\My Documents\F.pdf”)

                     Dim doc2 As New PdfDocument()

                     doc2.LoadFromFile(“D:\work\My Documents\G.pdf”)

                     ‘Create Template

                     Dim template As PdfTemplate = doc1.Pages(0).CreateTemplate()

                     For Each page As PdfPageBase In doc2.Pages

                           page.Canvas.SetTransparency(0.55f, 0.55f, PdfBlendMode.Overlay)

                           page.Canvas.DrawTemplate(template, PointF.Empty)

Nextpage

‘Save

                     doc2.SaveToFile(“Overlay.pdf”)

doc1.Close()

                     doc2.Close()

‘Launch

                     System.Diagnostics.Process.Start(“Overlay.pdf”)

              End Sub

       End Class

End Namespace

Result Shown by Following:

___________________________________________________________________________________________

Click Here to Learn more about Spire.PDF

Click Here to Download Spire.PDF

How to Draw Shapes in PDF – C#

When we write an article, we may need to insert some special symbols, such as triangle, star, arrow and so on. In this post, I will talk something about how to draw shape in PDF with C#.

In my example, I will draw stars and add colors for them on one blank PDF page. Actually, stars can be regard as being formed with five isosceles triangles around a pentagon. I will just add colors on triangles for the second star and have a color gradient effect with whole star for the third star. Then, the following steps will show details.

Before starting with steps, I need to add two references in my project. One is system.drawing and the other is Spire.PDF which I use to meet my requirement.

Steps:

1. Create a PDF document and add one page.

2. Define a method DrawPath to draw stars with colors to be convenient for using in main method.

  • For draw stars, we need to define 5 points and set their locations firstly. Then, add lines to connect them together.
  • Save graphics. Firstly, set format, including pen and brush colors. Secondly, set shapes scale and location. Then, draw the first star with format. Thirdly, draw the second star. Set location according to first star location. Then, set its fill mode and draw it with format. Finally, draw the third star as drawing the second star.
  • Restore graphics.

3. Use DrawPath method in main method and then save and launch file.

Main Coding:

using System;

using System.Drawing;

using Spire.Pdf;

using Spire.Pdf.Graphics;

namespace DrawShape

{

    class Shape

    {

        static void Main(string[] args)

        {

            //Create PDF

            PdfDocument doc = new PdfDocument();

            //Add Page

            PdfPageBase page = doc.Pages.Add();

            DrawPath(page);

            //Save File

            doc.SaveToFile(“DrawShape.pdf”);

            doc.Close();

            //Launch File

            System.Diagnostics.Process.Start(“DrawShape.pdf”);

        }

        private static void DrawPath(PdfPageBase page)

        {

            PointF[] points = new PointF[5];

            for (int i = 0; i < points.Length; i++)

            {

                float x = (float)Math.Cos(i * 2 * Math.PI / 5);

                float y = (float)Math.Sin(i * 2 * Math.PI / 5);

                points[i] = new PointF(x, y);

            }

            PdfPath path = new PdfPath();

            path.AddLine(points[2], points[0]);

            path.AddLine(points[0], points[3]);

            path.AddLine(points[3], points[1]);

            path.AddLine(points[1], points[4]);

            path.AddLine(points[4], points[2]);

            //Save Graphics

            PdfGraphicsState state = page.Canvas.Save();

            PdfPen pen = new PdfPen(Color.LightSeaGreen, 0.015f);

            PdfBrush brush1 = new PdfSolidBrush(Color.MediumTurquoise);

            page.Canvas.ScaleTransform(45f, 45f);

            page.Canvas.TranslateTransform(4f, 1.5f);

            page.Canvas.DrawPath(pen, path);

            page.Canvas.TranslateTransform(2f, 0f);

            path.FillMode = PdfFillMode.Alternate;

            page.Canvas.DrawPath(pen, brush1, path);

            PdfLinearGradientBrush brush2

                = new PdfLinearGradientBrush(new PointF(-2, 0), new PointF(2, 0), Color.LimeGreen, Color.AliceBlue);

            page.Canvas.TranslateTransform(2f, 0f);

            path.FillMode = PdfFillMode.Winding;

            page.Canvas.DrawPath(pen, brush2, path);

            //Restore Graphics

            page.Canvas.Restore(state);

        }

    }

}

Result Shown by Following:

______________________________________________________________________________________________

Click Here to Learn more about Spire.PDF

Click Here to Download Spire.PDF

Way to Manage PDF Page Setup for Printing with C#

Before printing one document, we need to do some setting on page according to document contents and page size. When printing, we hope that there will be a good layout and all the contents in document can be displayed on papers. However, it is possible that some contents will disappear or we cannot get contents clearly if we don’t pay attention to page setup. In this post, I will talk something about PDF page setup with C#.

Page setup includes page size and direction setting. In my example, I will set page size as A3 and A4. For direction, besides portrait and landscape, the page will be rotated, containing 90 and 180 degree. The following steps and code show you details.

In order to realize this function more quickly and easily, I use a C# .NET PDF component, Spire.PDF for .NET. So,  I have added its dll file as reference in my project. 

Steps:

  1. Create a PDF document and then set margin, including bottom, top, left and right.
  2. Before setting pages, we need to add some contents. The contents I draw are from wiki. Therefore, after adding title, add reference below title and use brackets to mark it. Next, load icon and body from my computer. Set them format to make the appearance be more wonderful.
  3. Create sections in pages. Set margin, page size and background color for this section. Then, draw page.
  4. Set page to rotate 180 degree, page size as A4. Add background color and draw page.
  5. Set direction of page as landscape, page size as A4. Add background color and draw page.
  6. Set page to rotate 90 degree, page size as A4. Add background color and draw page.
  7. Set page to rotate 180 degree, page size as A3, page direction as landscape. Add background color and draw page.
  8. Save and launch file.

Main Coding:

using System;
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;

namespace PageSetup
{
    class Setup
    {
        static void Main(string[] args)
        {
            //Create PDF.
            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;

            //Add Section
            PdfSection section = doc.Sections.Add();
            section.PageSettings.Size = PdfPageSize.A4;
            section.PageSettings.Margins = margin;
            PdfPageBase page = section.Pages.Add();
            page.BackgroundColor = Color.LightCyan;
            DrawPage(page);

            //Rotate 180
            section = doc.Sections.Add();
            section.PageSettings.Size = PdfPageSize.A4;
            section.PageSettings.Margins = margin;
            section.PageSettings.Rotate = PdfPageRotateAngle.RotateAngle180;
            page = section.Pages.Add();
            page.BackgroundColor = Color.LightCyan;
            DrawPage(page);

            //Landscape
            section = doc.Sections.Add();
            section.PageSettings.Size = PdfPageSize.A4;
            section.PageSettings.Margins = margin;
            section.PageSettings.Orientation = PdfPageOrientation.Landscape;
            page = section.Pages.Add();
            page.BackgroundColor = Color.LightSeaGreen;
            DrawPage(page);

            //Rotate 90
            section = doc.Sections.Add();
            section.PageSettings.Size = PdfPageSize.A4;
            section.PageSettings.Margins = margin;
            section.PageSettings.Rotate = PdfPageRotateAngle.RotateAngle90;
            page = section.Pages.Add();
            page.BackgroundColor = Color.LightCyan;
            DrawPage(page);

            //A3 Size, Rotate 180
            page = doc.Pages.Add(PdfPageSize.A3, margin, PdfPageRotateAngle.RotateAngle180, PdfPageOrientation.Landscape);
            page.BackgroundColor = Color.LightSeaGreen;
            DrawPage(page);

            //Save and Launch PDF
            doc.SaveToFile(“PageSetup.pdf”);
            doc.Close();
            System.Diagnostics.Process.Start(“PageSetup.pdf”);
        }

        private static void DrawPage(PdfPageBase page)
        {
            float pageWidth = page.Canvas.ClientSize.Width;
            float y = 0;

            //Title
            y = y + 20;
            PdfBrush brush2 = new PdfSolidBrush(Color.DarkBlue);
            PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font(“Calibri”, 14f, FontStyle.Regular));
            PdfStringFormat format2 = new PdfStringFormat(PdfTextAlignment.Center);
            format2.CharacterSpacing = 1f;
            String text = “Someone Like You”;
            page.Canvas.DrawString(text, font2, brush2, pageWidth / 2, y, format2);
            SizeF size = font2.MeasureString(text, format2);
            y = y + size.Height + 6;

            //Icon
            PdfImage image = PdfImage.FromFile(@”D:\work\My Documents\Adele.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;

            //Reference
            PdfTrueTypeFont font3 = new PdfTrueTypeFont(new Font(“Calibri”, 11f));
            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(“Calibri”, 11f, FontStyle.Underline));
            PdfBrush brush3 = PdfBrushes.DarkCyan;
            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(PdfTextAlignment.Justify);
            text = System.IO.File.ReadAllText(@”D:\work\My Documents\Someone Like You.txt”);
            PdfTrueTypeFont font5 = new PdfTrueTypeFont(new Font(“Calibri”, 11f));
            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);
                y = y + result.LineHeight;
            }

            PdfTextWidget textWidget = new PdfTextWidget(result.Remainder, font5, brush2);
            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);
        }
    }
}

Result Shown by Following:

 Download Spire.PDF for .NET Here

Encrypt PDF Document and Set Permissions – C#/VB.NET

Sometimes, we may find that our documents which are submitted to internet are edited by others, even someone steal it and write his/her name as author in documents. It lets us depressed. Therefore, it is necessary to protect our documents. In this post, I will introduce one method to encrypt PDF by C#/VB.NET.

How to protect document? The frequently used method is to encrypt it. Owner gives a password for document. People, including owner must use correct password to open document. Also, owner can set permissions for document, for example, allowing to printing.

In my example, I prepare a PDF document. I want to encrypt it and the password for me and others are different. After opening it, I will set other two permissions, allowed to printing and filling fields.

Then, let's go to steps. Because I use Spire.PDF in this method, so I add its dll file as reference at the beginning.

  1. Load PDF document from my computer.
  2. Encrypt PDF. Firstly, set password length. Secondly, set owners password and others password. Thirdly, set permissions.
  3. Save and launch new document.

Main Coding:

C#

using System;

using Spire.Pdf;

using Spire.Pdf.Security;

namespace EncryptPDF

{

    class Encryption

    {

        static void Main(string[] args)

        {

            //Load File

            PdfDocument doc = new PdfDocument();

            doc.LoadFromFile(@"D:\work\My Documents\Shelley.pdf");

 

            //encrypt

            doc.Security.KeySize = PdfEncryptionKeySize.Key128Bit;

            doc.Security.OwnerPassword = "123456";

            doc.Security.UserPassword = "654321";

            doc.Security.Permissions = PdfPermissionsFlags.Print | PdfPermissionsFlags.FillFields;

 

            //Save and Launch File

            doc.SaveToFile("Encryption.pdf");

            doc.Close();

            System.Diagnostics.Process.Start("Encryption.pdf");

        }

    }

}

VB.NET

Imports System

Imports Spire.Pdf

Imports Spire.Pdf.Security

Namespace EncryptPDF

       Friend Class Encryption

              Shared Sub Main(ByVal args() As String)

                     'Load File

                     Dim doc As New PdfDocument()

                     doc.LoadFromFile("D:\work\My Documents\Shelley.pdf")

 

                     'encrypt

                     doc.Security.KeySize = PdfEncryptionKeySize.Key128Bit

                     doc.Security.OwnerPassword = "123456"

                     doc.Security.UserPassword = "654321"

                     doc.Security.Permissions = PdfPermissionsFlags.Print Or PdfPermissionsFlags.FillFields

 

                     'Save and Launch File

                     doc.SaveToFile("Encryption.pdf")

                     doc.Close()

                     System.Diagnostics.Process.Start("Encryption.pdf")

              End Sub

       End Class

End Namespace

Result Shown by Following:

___________________________________________________________________________________

Click Here to Learn more about Spire.PDF

Click Here to Download Spire.PDF