[]
DsExcel provides the PdfSaveOptions class for customizing PDF files exported from Excel workbooks and worksheets. You can use these options to control the appearance, layout, metadata, security, and export behavior of the generated PDF document.
Class | Option | Description |
|---|---|---|
Specifies the border width and dash pattern for specific line styles in the exported PDF. | ||
Specifies PDF properties such as the title, author, subject, keywords, dates, and PDF version. | ||
Indicates whether supported Excel form controls are exported as interactive PDF form fields. The default value is false. Not all controls and properties are supported. | ||
Sets the image quality in percent. This value must be between 0 (lowest quality, maximum compression) and 100 (highest quality, no compression). The default value is 75. | ||
Specifies the JavaScript that runs when the exported PDF is opened. | ||
Indicates whether to print the sheet's background image on the page. | ||
Indicates whether to print the transparency of the cell's background color on the page. | ||
Specifies PDF passwords and permissions, such as whether users can print, modify, or extract content. | ||
The settings about performing shrink to fit on the wrapped text. | ||
The settings that contain information specifying how the current document should be displayed. | ||
Indicates whether cell regions created by automatic merging are included in the exported PDF. The default value is false. | ||
Occurs after a page is exported to PDF. Use this event to track export progress or stop the export by setting the HasMorePages property of PagePrintedEventArgs. | ||
Occurs before a page is exported to PDF. Use this event to track export progress or skip the current page by setting the SkipThisPage property of PagePrintingEventArgs. |
DsExcel enables you to export PDF documents with a custom border style using BorderOptions property of PdfSaveOptions class. This property uses BorderWidth and Dashes properties of CustomBorderStyle class and BorderLineStyle enumeration to set the border width, dash length, and line style.
CustomBorderStyle.BorderWidth: Sets the width of the border when exporting a PDF document.
CustomBorderStyle.Dashes: Sets the length of each segment in a dashed line.
BorderLineStyle: Specifies the line style of the border.
The following table lists the default values of all the border styles:
Border Type | Default Line Width (point) | Dashes (point) | Comment |
|---|---|---|---|
Hair | 0.2 | None | - |
DashDotDot | 1 | 9,3,3,3,3,3 | - |
DashDot | 1 | 8,2,2,2 | - |
Dotted | 1 | 1,1 | - |
Dashed | 1 | 3,1 | - |
Thin | 1 | None | - |
MediumDashDotDot | 2 | 4.5,1.5,1.5,1.5,1.5,1.5 | - |
SlantDashDot | 1 | 11, 1,5,1 | This border type comprises two lines, each with a width of 1 point. |
MediumDashDot | 2 | 4.5,1.5,1.5,1.5 | - |
MediumDashed | 2 | 4.5,1.5 | - |
Medium | 2 | None | - |
Thick | 3 | None | This border type comprises three lines, each with a width of 1 point. |
Double | 1 | None | This border type comprises two lines, each with a width of 1 point. |
Refer to the following example code to adjust the border width, dash length, and line style when exporting to a PDF document:
// Create a new workbook.
var workbook = new Workbook();
// Open template file.
workbook.Open("CustomBorderStyle.xlsx");
// Customize the border style for PDF export.
// Initialize PdfSaveOptions.
var pdfSaveOptions = new PdfSaveOptions();
// Set outer border width to 0.4.
var thinBorderSetting = new CustomBorderStyle { BorderWidth = 0.4 };
// Set middle border width to 1.5.
var middleBorderSetting = new CustomBorderStyle { BorderWidth = 1.5 };
// Set inner horizontal border width to 0.4 in dash style.
var dashBorderSetting = new CustomBorderStyle { BorderWidth = 0.4, Dashes = new List<double> { 0.8, 0.8 } };
// Add borders with custom border styles.
pdfSaveOptions.BorderOptions.Add(BorderLineStyle.Thin, thinBorderSetting);
pdfSaveOptions.BorderOptions.Add(BorderLineStyle.Medium, middleBorderSetting);
pdfSaveOptions.BorderOptions.Add(workbook.ActiveSheet.Range["B13"].Borders[BordersIndex.EdgeTop].LineStyle, dashBorderSetting);
// Save workbook to PDF file.
workbook.Save("CustomBorder.pdf", pdfSaveOptions);
DsExcel supports applying the Shrink to Fit feature to cells with wrapped text when exporting Excel files to PDF. This feature automatically reduces the font size so that the wrapped text can fit within the cell without requiring changes to row height or column width.
This is useful for worksheets with limited vertical space or tightly controlled layouts, especially when you do not want to use Auto Fit row height or column width.
The following properties control how Shrink to Fit is applied to wrapped text during PDF export:
Property | Description |
|---|---|
Gets or sets the settings for applying Shrink to Fit to wrapped text during PDF export. | |
Gets or sets whether Shrink to Fit is applied to wrapped text. If set to true, the font size may be reduced so that the wrapped text can be fully displayed. | |
Gets or sets the minimum font size allowed when Shrink to Fit is applied. | |
Gets or sets the omitted string to display when the wrapped text still cannot be fully displayed. This can be used together with MinimumFont. |
Refer to the following example code to allow users to use the shrink to fit feature with text wrap.
// Create a PDF file stream.
using FileStream outputStream =
new FileStream("ShrinkToFitForWrappedText.pdf", FileMode.Create);
// Create a new workbook.
var workbook = new GrapeCity.Documents.Excel.Workbook();
IWorksheet worksheet = workbook.Worksheets[0];
worksheet.PageSetup.PrintGridlines = true;
worksheet.PageSetup.PrintHeadings = false;
// Configure the table layout.
worksheet.Range["A:B"].ColumnWidth = 14;
worksheet.Range["1:1"].RowHeight = 30;
worksheet.Range["2:2"].RowHeight = 32;
// Add the table headers.
worksheet.Range["A1:B1"].Value = new object[,]
{
{ "Wrapped Text", "Shrink-to-Fit Wrapped Text" }
};
worksheet.Range["A1:B1"].Font.Bold = true;
worksheet.Range["A1:B1"].WrapText = true;
worksheet.Range["A1:B1"].HorizontalAlignment = HorizontalAlignment.Center;
worksheet.Range["A1:B1"].VerticalAlignment = VerticalAlignment.Center;
// Add the comparison content horizontally.
worksheet.Range["A2:B2"].Value = new object[,]
{
{
"Document Solutions for Excel",
"Document Solutions for Excel"
}
};
worksheet.Range["A2:B2"].WrapText = true;
worksheet.Range["A2:B2"].VerticalAlignment = VerticalAlignment.Center;
// Shrink the wrapped text in B2 to fit the existing cell size.
worksheet.Range["B2"].ShrinkToFit = true;
// Enable Shrink to Fit for wrapped text during PDF export.
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
pdfSaveOptions.ShrinkToFitSettings.CanShrinkToFitWrappedText = true;
// Optional settings.
// pdfSaveOptions.ShrinkToFitSettings.MinimumFont = 10;
// pdfSaveOptions.ShrinkToFitSettings.Ellipsis = "~";
// Save the workbook to PDF.
workbook.Save(outputStream, pdfSaveOptions);
PDF is a common format for sharing professional documents and often requires security controls such as user/owner passwords and permissions for printing, content copying, and annotations. When converting Excel spreadsheets to PDF, DsExcel supports these controls through the PdfSecurityOptions class, allowing you to restrict PDF access and operations based on specified security settings.
With DsExcel's PdfSecurityOptions class, you can restrict access to your PDF document, while converting Excel spreadsheet to PDF document. You can choose through the following security properties in the PdfSecurityOptions class:
Properties | Description |
|---|---|
Gets or sets the user password of the PDF document. | |
Gets or sets the owner password of the PDF document. This password is required to change the permissions for the PDF document. | |
Gets or sets the permission to print the PDF document. The default value is true for this property. | |
Gets or sets the permission to print in high quality. The default value is true for this property, and it only works when PrintPermission property is set to true. | |
Gets or sets the permission to copy or extract content. The default value is true for this property. | |
Gets or sets the permission to modify the PDF document. The default value is true for this property. | |
Gets or sets the permission to insert, rotate or delete pages, and create bookmarks/thumbnail images. The default value is true for this property. If you want to prevent a user from inserting, rotating or deleting pages, you need to set ModifyDocumentPermission property to false as well. | |
Gets or sets the permission to modify text annotations and fill the form fields. The default value is true for this property. | |
Gets or sets the permission to fill the form fields even if the ModifyAnnotationsPermission property returns false. The default value for this property is true. Note that if you want to prevent a user from filling interactive form fields, you need to set the ModifyAnnotationsPermission property to false. |
Refer to the following example to add security options while exporting Excel spreadsheets to PDF documents.
public void SavePDFPdfSecurityOptions()
{
// Initialize workbook
Workbook workbook = new Workbook();
// Fetch default worksheet
IWorksheet worksheet = workbook.Worksheets[0];
// Data
object[,] data = new object[,]{
{"Name", "City", "Birthday", "Sex", "Weight", "Height", "Age"},
{"Bob", "NewYork", new DateTime(1968, 6, 8), "male", 80, 180, 56},
{"Betty", "NewYork", new DateTime(1972, 7, 3), "female", 72, 168, 45},
{"Gary", "NewYork", new DateTime(1964, 3, 2), "male", 71, 179, 50},
{"Hunk", "Washington", new DateTime(1972, 8, 8), "male", 80, 171, 59},
{"Cherry", "Washington", new DateTime(1986, 2, 2), "female", 58, 161, 34},
{"Coco", "Virginia", new DateTime(1982, 12, 12), "female", 58, 181, 45},
{"Lance", "Chicago", new DateTime(1962, 3, 12), "female", 49, 160, 57},
{ "Eva", "Washington", new DateTime(1993, 2, 5), "female", 71, 180, 81}};
// Set data
worksheet.Range["A1:G9"].Value = data;
//The security settings of pdf when converting excel to pdf
PdfSecurityOptions securityOptions = new PdfSecurityOptions();
//Sets the user password
securityOptions.UserPassword = "user";
//Sets the owner password
securityOptions.OwnerPassword = "owner";
//Printing the pdf document is not allowed
securityOptions.PrintPermission = false;
//Filling the form fields of the pdf document is not allowed
securityOptions.FillFormsPermission = false;
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
//Sets the security settings of the pdf
pdfSaveOptions.SecurityOptions = securityOptions;
// Saving workbook to PDF
workbook.Save(@"4-SavePDFPdfSecurityOptions.pdf", pdfSaveOptions);
}After setting security options for the PDF, a password is required to open the PDF file.

Note: DsExcel uses RC4 encryption with key from 40 to 128 bit length and allows to define additional permission flags.
DsExcel provides support for document properties while saving Excel spreadsheets to PDF documents. The document properties contain the basic information about a document, such as title, author, creation date, subject, creator, version etc. You can store such useful information in the exported PDF document.
The DocumentProperties class contains the properties such as PdfVersion, EmbedStandardWindowsFonts, Title, Author, Subject, Keywords, Creator, Producer, CreationDate and ModifyDate.
Refer to the following example code to add document properties in a PDF document.
// Create a pdf file stream
FileStream outputStream = new FileStream("setdocumentpropertiestopdf.pdf", FileMode.Create);
// Create a new workbook
var workbook = new GrapeCity.Documents.Excel.Workbook();
IWorksheet worksheet = workbook.Worksheets[0];
worksheet.Range["A1"].Value = "Documents for Excel";
worksheet.Range["A1"].Font.Size = 25;
DocumentProperties documentProperties = new DocumentProperties
{
// Sets the name of the person that created the PDF document.
Author = "Jaime Smith",
// Sets the title of the PDF document.
Title = "GcPdf Document Info Sample",
// Do not embed a font.
EmbedStandardWindowsFonts = false,
// Set the PDF version.
PdfVersion = 1.5f,
// Set the subject of the PDF document.
Subject = "GcPdfDocument.DocumentInfo",
// Set the keyword associated with the PDF document.
Keywords = "Keyword1",
// Set the creation date and time of the PDF document.
CreationDate = DateTime.Now.AddYears(10),
// Set the date and time the PDF document was most recently modified.
ModifyDate = DateTime.Now.AddYears(11),
// Set the name of the application that created the original PDF document.
Creator = "GcPdfWeb Creator",
// Set the name of the application that created the PDF document.
Producer = "GcPdfWeb Producer"
};
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions
{
// Sets the document properties of the pdf.
DocumentProperties = documentProperties
};
// Save the workbook into pdf file.
workbook.Save(outputStream, pdfSaveOptions);
// Close the pdf stream
outputStream.Close();DsExcel supports sheet background image which can be included while exporting the worksheet to a PDF file. This is very useful for displaying company logos and watermarks in PDF documents.
In a worksheet, you can set a background image using the BackgroundPicture property of the IWorksheet interface.
The PrintBackgroundPicture property in PdfSaveOptions class renders the background image in the center of the page while exporting worksheet to PDF document.
Refer to the following example code to include sheet background image while exporting to PDF document.
// Initialize workbook.
Workbook workbook = new Workbook();
// Fetch default worksheet
IWorksheet worksheet = workbook.Worksheets[0];
worksheet.Range["A1"].Value = "Document Solutions for Excel";
worksheet.Range["A1"].Font.Size = 25;
using (FileStream pictureStream = File.Open(@"background-image.png", FileMode.Open, FileAccess.Read))
{
MemoryStream pictureMemoryStream = new MemoryStream();
pictureStream.CopyTo(pictureMemoryStream);
byte[] picturebytes = pictureMemoryStream.ToArray();
//Add background image of the worksheet
worksheet.BackgroundPicture = picturebytes;
}
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
// Print the background picture in the centre of exported pdf file.
pdfSaveOptions.PrintBackgroundPicture = true;
// Saving workbook to pdf.
workbook.Save(@"PrintBackgroundPicture.pdf", pdfSaveOptions);
Multiple background images can be rendered in DsExcel using the BackgroundPictures property of the IWorksheet interface. These images can be included while exporting the worksheet to PDF documents. The background images in PDF are drawn based on the gridlines and can be positioned anywhere in the document by specifying the coordinates of the destination rectangle.
Further, the image transparency, border, corner radius and other formatting options can also be applied. For setting the corner radius, the minimum value is 0 and the maximum value is the height or width (whichever is smaller) of the destination rectangle divided by two. The ImageLayout enum can be used to specify the way the image should be placed to fill the destination rectangle in PDF.
Refer to the following example code to include multiple background images while exporting to PDF document.
// Initialize workbook.
Workbook workbook = new Workbook();
IWorksheet worksheet = workbook.Worksheets[0];
// Add two background pictures in the worksheet
IBackgroundPicture picture1 = worksheet.BackgroundPictures.AddPictureInPixel("logo.png", 100, 100, 350, 250);
IBackgroundPicture picture2 = worksheet.BackgroundPictures.AddPictureInPixel("watermark.png", 180, 10, 150, 100);
// Set the border style of the destination rectangle
picture1.Line.Color.RGB = Color.Gray;
picture1.Line.Weight = 1;
// The background picture will be resized to fill the destination dimensions.The aspect ratio is not preserved.
picture1.BackgroundImageLayout = ImageLayout.Stretch;
// Sets the rounded corner of the destination rectangle.
picture1.CornerRadius = 50;
// Sets the transparency of the background pictures.
picture1.Transparency = 0.5;
picture2.Transparency = 0.5;
// Save to PDF file.
workbook.Save("ExportBackgroundImageToPDF.pdf");
When backcolor is applied on a cell or range, any background image or data gets hidden behind it while exporting to PDF.
DsExcel allows you to make the cell's backcolor transparent when exported to PDF by using the PrintTransparentCell property of the PdfSaveOptions class. The default value of this property is false. When set to true, it prints the transparency of the cell's background color which makes any background image or data visible.
Refer to the following example code to make cell's backcolor transparent to view the background image in PDF document.
// Initialize workbook.
Workbook workbook = new Workbook();
// Fetch default worksheet.
IWorksheet worksheet = workbook.Worksheets[0];
// Set the background color of range ["A1:K20"].
worksheet.Range["A1:K20"].Interior.Color = System.Drawing.Color.FromArgb(50, 255, 0, 0);
// Add a background picture.
IBackgroundPicture picture = worksheet.BackgroundPictures.AddPictureInPixel("image.png", 0, 0, 300, 200);
// Set the transparency of cell's background color, so the background picture will come out to the front.
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
pdfSaveOptions.PrintTransparentCell = true;
// Save to pdf file.
workbook.Save("PrintTransparentCell.pdf", pdfSaveOptions);
DsExcel provides PagePrinting and PagePrinted events in PdfSaveOptions class to track the export progress of a workbook to PDF. The PagePrinting event occurs before printing a page and provides SkipThisPage property to skip pages while exporting. Similarly, the PagePrinted event occurs after printing a page and provides HasMorePages property to exit PDF exporting.
Refer to the following example code to display the export progress of a workbook to PDF.
// Create a pdf file stream.
FileStream outputStream = new FileStream("pageprinteventstrackprogress.pdf", FileMode.Create);
// Create a new workbook.
var workbook = new Workbook();
var activeSheet = workbook.ActiveSheet;
activeSheet.Range["A1"].Value = 1;
activeSheet.Range["A2:A100"].FormulaR1C1 = "=R[-1]C+1";
var options = new PdfSaveOptions();
options.PagePrinting += (sender, e) =>
Console.WriteLine($"Printing page {e.PageNumber} of {e.PageCount}");
activeSheet.PageSetup.CenterHeader = "Page &P of &N";
workbook.Save(outputStream, options);
// Close the pdf stream.
outputStream.Close();Refer to the following example code to skip second page while exporting a workbook to PDF.
// Create a pdf file stream.
FileStream outputStream = new FileStream("pageprinteventsskippage.pdf", FileMode.Create);
// Create a new workbook.
var workbook = new GrapeCity.Documents.Excel.Workbook();
var activeSheet = workbook.ActiveSheet;
activeSheet.Range["A1"].Value = 1;
activeSheet.Range["A2:A100"].FormulaR1C1 = "=R[-1]C+1";
var options = new PdfSaveOptions();
// skip second page.
options.PagePrinting += (sender, e) =>
{
if (e.PageNumber == 2)
{
e.SkipThisPage = true;
}
};
activeSheet.PageSetup.CenterHeader = "Page &P of &N";
workbook.Save(outputStream, options);
// Close the pdf stream
outputStream.Close();Refer to the following example code to exit PDF exporting after second page.
// Create a pdf file stream.
FileStream outputStream = new FileStream("pageprinteventsexitprinting.pdf", FileMode.Create);
// Create a new workbook.
var workbook = new GrapeCity.Documents.Excel.Workbook();
var activeSheet = workbook.ActiveSheet;
activeSheet.Range["A1"].Value = 1;
activeSheet.Range["A2:A100"].FormulaR1C1 = "=R[-1]C+1";
var options = new PdfSaveOptions();
// Exit printing after second page.
options.PagePrinted += (sender, e) =>
{
if (e.PageNumber == 2)
{
e.HasMorePages = false;
}
};
activeSheet.PageSetup.CenterHeader = "Page &P of &N";
workbook.Save(outputStream, options);
// Close the pdf stream.
outputStream.Close();DsExcel supports setting JavaScript in PDF documents by using OpenActionScript property of PdfSaveOptions class. The JavaScript is executed when the saved PDF document is opened.
Refer to the following example code to set JavaScript in an Excel template which is processed to create a PDF form:
Workbook workbook = new Workbook();
workbook.Open("SampleTemplate.xlsx");
workbook.ProcessTemplate();
PdfSaveOptions options = new PdfSaveOptions();
// Set JavaScript.
options.OpenActionScript = "var fld1 = this.getField(\"num\");" +
"fld1.value = fld1.value;" +
"this.dirty = false;";
workbook.Save("SampleTemplate.pdf", options);DsExcel enables users to control the quality of images while exporting them to PDF documents. The ImageQuality property of PdfSaveOptions class can be used for the same. The property takes percentage values and its default value is 75. However, it can vary between 0 to 100, depicting the below behavior:
Value | Image Quality | Image Compression |
|---|---|---|
0 | Lowest | Maximum |
100 | Highest | None |
Refer to the following example code to export an image to PDF with highest image quality.
// Initialize workbook.
Workbook workbook = new Workbook();
// Fetch default worksheet
IWorksheet worksheet = workbook.Worksheets[0];
// Add a picture.
worksheet.Shapes.AddPictureInPixel("Logo.png", 0, 0, 639, 578);
// Create PdfSaveOptions.
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
// Set image quality as 100 % (highest quality).
pdfSaveOptions.ImageQuality = 100;
// Save to pdf with PdfSaveOptions.
workbook.Save("LogoInPDF.pdf", pdfSaveOptions);DsExcel allows users to configure fonts and set style while saving their worksheets into the PDF format.
Before performing the export operation, users need to ensure that they set the FontsFolderPath property of the Workbook class in order to specify the font that should be used while saving the PDF.
If the folder path to the font is not specified and the user is working on Windows OS, the path "C:\Windows\Fonts" will be used by default. However, if the folder path to the font is not specified and the user is working on any other operating system, it is necessary that the user sets the font folder path and copies the used font files to it from the folder "C:\Windows\Fonts".
You can use the GetUsedFonts method of the Workbook class in order to get the collection of all the fonts that are used in the workbook.
While saving PDF, DsExcel uses the fonts specified in the Workbook.FontsFolderPath in order to render the PDF. However, if the used font doesn't exist, it will make use of some fallback fonts. In case, fallback fonts don't exist in the file, DsExcel will throw the exception :"There is no available fonts. Please set a valid path to the FontsFolderPath property of the Workbook!"
Refer to the following example code to see how you can confirgure fonts and set style while saving to a PDF.
// Create workbook and add two sheets.
Workbook workbook = new Workbook();
IWorksheet sheet1 = workbook.Worksheets[0];
IWorksheet sheet2 = workbook.Worksheets.Add();
// Set style.
sheet1.Range["A1"].Value = "Sheet1";
sheet1.Range["A1"].Font.Name = "Wide Latin";
sheet1.Range["A1"].Font.Color = Color.Red;
sheet1.Range["A1"].Interior.Color = Color.Green;
// Create a table in sheet1.
sheet1.Tables.Add(sheet1.Range["C1:E5"], true);
sheet2.Range["A1"].Value = "Sheet2";
// Specify font path.
Workbook.FontsFolderPath = @"D:\Fonts";
// Get the used fonts list in workbook, the list are:"Wide Latin", "Calibri"
var fonts = workbook.GetUsedFonts();
// Export workbook to pdf file, the exported file has two pages.
workbook.Save(@"D:\workbook.pdf", SaveFileFormat.Pdf);
// Just export sheet1 to pdf file.
sheet1.Save(@"D:\sheet1.pdf", SaveFileFormat.Pdf);Limitations
The Export to PDF feature doesn't support the following styles:
SingleAccounting and DoubleAccounting underline styles
Superscript and subscript
Alignment settings such as Fill, Orientation, and text reading order
Rectangular gradient fill