Copied RSS Feed

.NET

What’s New in 2018 Volume 2: File Formats

Syncfusion’s file format libraries get exciting updates (new features and enhancements) in the Essential Studio® release 2018 Volume 2. Most of these items have been included based on your valuable feedback. Syncfusion’s file format libraries provide .NET class libraries to create, edit, write, and convert Excel, PDF, Word, and PowerPoint file formats in the .NET Framework, Xamarin, .NET Core, and UWP applications without Microsoft Office or Adobe dependencies.

In this blog, let me walk you through the new items included in the 2018 Volume 2 release for our file formats libraries.

Essential PDF

Right-to-left text in Xamarin and .NET Core

Essential PDF allows you to add right-to-left (RTL) text (Arabic, Hebrew, Urdu) and bi-directional (bidi) in PDF documents in Xamarin and .NET Core applications.

The following code example shows how to draw RTL and bi-directional text.

//Create a new PDF document.
PdfDocument document = new PdfDocument();

//Add a new PDF page.
PdfPage page = document.Pages.Add();

//Create new PdfTrueTypeFont instance.
//Load the font from assets.
Stream fontStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("RTLDemo.Assets.arial.ttf");
PdfTrueTypeFont font = new PdfTrueTypeFont(fontStream, 12);

//Create a PdfStringFormat.
PdfStringFormat format = new PdfStringFormat();

//Set text direction.
format.TextDirection = PdfTextDirection.RightToLeft;

//Set text alignment.
format.Alignment = PdfTextAlignment.Right;

//Draw text to the PDF document.
page.Graphics.DrawString("مرحبا بالعالم!",font, PdfBrushes.Black, Syncfusion.Drawing.PointF.Empty, format);

//Save document. 
MemoryStream ms = new MemoryStream();
document.Save(ms);

//Close the PdfDocument instance.
document.Close(true);

PDF to PDF/A-1b conversion

Now, you can convert an existing PDF document to a PDF/A-1b conformance level that ensures the document’s visual appearance looks the same as always.
//Load an existing PDF.
PdfLoadedDocument loadedDocument = new PdfLoadedDocument("Input.pdf");

//Set the conformance for PDF/A-1b conversion.
loadedDocument.Conformance = PdfConformanceLevel.Pdf_A1B;

//Save and close the document.
loadedDocument.Save("Output.pdf");
loadedDocument.Close(true);

Digital signature enhancements

  • You can flatten the existing PDF digital signature fields to remove the digital signature assigned to the signature field.
  • You can add time stamps to the PDF document without using a certificate in .NET Core.
//Create a new PDF document.
PdfDocument document = new PdfDocument();

//Add a new page.
PdfPage page = document.Pages.Add();

//Creates a digital signature.
PdfSignature signature = new PdfSignature(page, "Signature");

//Add the time stamp by using the server URI.
signature.TimeStampServer = new TimeStampServer(new Uri("http://syncfusiontest.timestamp.com"));

//Save and close the document.
document.Save("output.pdf");

document.Close(true);

  • You can sign a PDF document from the local certificate store in .NET Core applications.
//Create a new PDF document.
PdfDocument document = new PdfDocument();

//Adds a new page.
PdfPage page = document.Pages.Add();

//Creates a certificate instance from PFX file with private key.
X509Certificate2 cert = new X509Certificate2(@"PDF.pfx", "syncfusion");

PdfCertificate pdfCert = new PdfCertificate(cert);

//Creates a digital signature.
PdfSignature signature = new PdfSignature(document, page, pdfCert, "Signature");

//Sets signature information.
signature.Reason = "Support X509certificate2";

MemoryStream stream = new MemoryStream();

//Saves the stream.
document.Save(stream);

//Creates new file for store the stream.
FileStream file = new FileStream(@"X509cert.pdf", FileMode.Create, FileAccess.Write);

//Writes the stream
stream.WriteTo(file);

//Closes the stream and document.
file.Close();
document.Close();

Adding annotations to PDF layers

Already, Essential PDF supports adding annotations to PDF documents. Now, this is extended to add annotations into PDF layers, which is used to add optional content to PDF documents; it can be selectively viewed or hidden by the user. To learn more about PDF layers, please refer to this documentation.

//Create new PDF document.
PdfDocument document = new PdfDocument();

//Add page.
PdfPage page = document.Pages.Add();

//Create layer.
PdfLayer layerGreen = document.Layers.Add("Green");

//Create graphics for layerGreen.
PdfGraphics graphics = layerGreen.CreateGraphics(page);

//Draw ellipse.
graphics.DrawEllipse(PdfPens.Gold, new RectangleF(50, 50, 40, 40));

//Create square annotation.
PdfSquareAnnotation annotation = new PdfSquareAnnotation(new RectangleF(200, 260, 50, 50), "Square annotation");
annotation.Color = new PdfColor(System.Drawing.Color.Gold);

//Set layer to annotation.
annotation.Layer = layerGreen;
page.Annotations.Add(annotation);

//Save the document.
document.Save("Output.pdf");
document.Close(true);

Export PDF form data as FDF, XFDF, JSON and XML

Essential PDF introduces the support to export PDF AcroForm data as FDF (Forms Data format), XFDF (XML based alternative to FDF), JSON and XML formats in Xamarin and .NET Core applications. Now you can fill the data or save the data filled using ImportData and ExportData methods of PdfLoadedForm for further processing.
// Load the PDF document.
PdfLoadedDocument document = new PdfLoadedDocument("AcroformData.pdf");

// Get the form fields.
PdfLoadedForm form = document.Form;

// Export it to FDF.
MemoryStream memoryStream = new MemoryStream();
form.ExportData(memoryStream, DataFormat.Fdf, "AcroformData.pdf");

document.Close();

Load IEnumerable collection in PDF table

In PDF tables (PdfGrid and PdfLightTable), you can load and populate the data from an IEnumerable collection. This support already available for Xamarin, .NET Core, and UWP applications, and now it has been extended to .NET Framework platforms (WinForms, WPF, ASP.NET, and ASP.NET MVC).
//Create a new PDF document.
PdfDocument doc = new PdfDocument();

//Add a page.
PdfPage page = doc.Pages.Add();

//Create a PdfGrid.
PdfGrid pdfGrid = new PdfGrid();
List<object> data = new List<object>();
dynamic r1 = new { ID = "1", Name = "Clay" };
dynamic r2 = new { ID = "2", Name = "Gray" };
dynamic r3 = new { ID = "3", Name = "Ash" };
data.Add(r1);
data.Add(r2);

IEnumerable<object> tableData = data;
pdfGrid.DataSource = tableData;

//Draw grid to the page of PDF document.
pdfGrid.Draw(page, new PointF(10, 10));

//Save the document.
doc.Save("Sample.pdf");

//Close the document.
doc.Close(true);

Custom metadata or document properties

Apart from the predefined document information fields, you can add and edit the custom document information fields or metadata. This enables you to store more information about the PDF document.

//Create new PDF document.
PdfDocument pdfDoc = new PdfDocument()

//Add new PDF page.
PdfPage page = pdfDoc.Pages.Add();

//Add Custom MetaData.
pdfDoc.DocumentInformation.CustomMetadata["Language"] = "English";
pdfDoc.DocumentInformation.CustomMetadata["Country"] = "US";
pdfDoc.DocumentInformation.CustomMetadata["Publisher"] = "Syncfusion";

//Save document.
pdfDoc.Save("AddCustomField.pdf");
//Close Document
pdfDoc.Close(true);

Essential XlsIO

DataTable support in .NET Core 2.0

Importing and exporting data from and to DataTable are commonly used features in XlsIO and are supported in Windows Forms, WPF, ASP.NET and ASP.NET MVC platforms already. In addition, XlsIO now supports importing and exporting data from and to DataTable in the ASP.NET Core 2.0 platform. The APIs are same as in other platforms; please refer to this guide.

Grouping shapes support in XLSX format

Grouping shapes can be used to work with multiple shapes in a single instant. For example, you can change positions and size, or set colors for all the shapes at the same time through a single grouping of shapes.

The following code example illustrates how to group multiple shapes.

using (ExcelEngine excelEngine = new ExcelEngine())
{
 IApplication application = excelEngine.Excel;
 IWorkbook workbook = application.Workbooks.Open("GroupShape.xlsx");
 IWorksheet worksheet = workbook.Worksheets[0];

 IShapes shapes = worksheet.Shapes;

 // Select the shapes you want to group.
 IShape[] groupItems = new IShape[] { shapes[0], shapes[1] };

 // Group the selected shapes
 IGroupShape GroupShape = shapes.Group(groupItems);

 workbook.SaveAs("GroupShape.xlsx");
}

Ungroup shapes

Grouped shapes can be ungrouped, and their inner shapes will be added to worksheet as individual shapes.

using (ExcelEngine excelEngine = new ExcelEngine())
{
 IApplication application = excelEngine.Excel;
 IWorkbook workbook = application.Workbooks.Open("GroupShape.xlsx");
 IWorksheet worksheet = workbook.Worksheets[0];

 IShapes shapes = worksheet.Shapes;

 // Ungroup the selected specified group shape
 shapes.Ungroup(shapes[0] as IGroupShape);

 workbook.SaveAs("GroupShape.xlsx");
}

Ungroup all the shapes

The following code example illustrates how to ungroup all the grouped shapes in a collection.

using (ExcelEngine excelEngine = new ExcelEngine())
{
 IApplication application = excelEngine.Excel;
 IWorkbook workbook = application.Workbooks.Open("GroupShape.xlsx");
 IWorksheet worksheet = workbook.Worksheets[0];

 IShapes shapes = worksheet.Shapes;

 // Ungroup the selected specified group shape and its inner shapes by specifying isAll property.
 shapes.Ungroup(shapes[0] as IGroupShape, true);

 workbook.SaveAs("GroupShape.xlsx");
}

Support for AutoShapes in Excel to PDF

Excel documents with AutoShapes can be converted to the resultant PDF in the upcoming release and data loss will be avoided. The existing code that converts Excel to PDF will take care of AutoShapes, too.

Support for Repeat Item Labels in pivot table layout

Pivot table supports various layout options to visualize reports. Similarly, the Repeat All Item Labels option enables the view that repeats data for a specific field that is set to tabular or outline forms.

The labels can be repeated to a specific field

using (ExcelEngine excelEngine = new ExcelEngine())
{
 IApplication application = excelEngine.Excel;
 IWorkbook workbook = application.Workbooks.Open("Sample.xlsx");
 workbook.Version = ExcelVersion.Excel2013;
 IWorksheet worksheet = workbook.Worksheets[0];
 IWorksheet pivotSheet = workbook.Worksheets[1];

 //Create pivot table.
 IPivotCache cache = workbook.PivotCaches.Add(worksheet["A1:H50"]);
 IPivotTable pivotTable = pivotSheet.PivotTables.Add("PivotTable1", pivotSheet["A1"], cache);
 pivotTable.Fields[1].Axis = PivotAxisTypes.Row;
 pivotTable.Fields[2].Axis = PivotAxisTypes.Row;
 pivotTable.Fields[4].Axis = PivotAxisTypes.Row;
 pivotTable.Fields[3].Axis = PivotAxisTypes.Column;
 pivotTable.Fields[5].Axis = PivotAxisTypes.Column;

 IPivotField field = pivotSheet.PivotTables[0].Fields[7];
 pivotTable.DataFields.Add(field, "Sum of Units", PivotSubtotalTypes.Sum);
 pivotTable.ShowDrillIndicators = true;
 pivotTable.RowGrand = false;
 pivotTable.DisplayFieldCaptions = true;
 pivotTable.BuiltInStyle = PivotBuiltInStyles.PivotStyleMedium2;

 //Set layout.
 pivotTable.Options.RowLayout = PivotTableRowLayout.Tabular;

 //Set repeat labels to specific fields.
 pivotTable.Fields[1].RepeatLabels = true;
 pivotTable.Fields[2].RepeatLabels = true;

 //Save workbook.
 workbook.SaveAs("Output.xlsx");
}

The labels can be set to all fields

using (ExcelEngine excelEngine = new ExcelEngine())
{
 IApplication application = excelEngine.Excel;
 IWorkbook workbook = application.Workbooks.Open("Sample.xlsx");
 workbook.Version = ExcelVersion.Excel2013;
 IWorksheet worksheet = workbook.Worksheets[0];
 IWorksheet pivotSheet = workbook.Worksheets[1];

 //Create pivot table.
 IPivotCache cache = workbook.PivotCaches.Add(worksheet["A1:H50"]);
 IPivotTable pivotTable = pivotSheet.PivotTables.Add("PivotTable1", pivotSheet["A1"], cache);
 pivotTable.Fields[1].Axis = PivotAxisTypes.Row;
 pivotTable.Fields[2].Axis = PivotAxisTypes.Row;
 pivotTable.Fields[4].Axis = PivotAxisTypes.Row;
 pivotTable.Fields[3].Axis = PivotAxisTypes.Column;
 pivotTable.Fields[5].Axis = PivotAxisTypes.Column;
 IPivotField field = pivotSheet.PivotTables[0].Fields[7];
 pivotTable.DataFields.Add(field, "Sum of Units", PivotSubtotalTypes.Sum);
 pivotTable.ShowDrillIndicators = true;
 pivotTable.RowGrand = false;
 pivotTable.DisplayFieldCaptions = true;
 pivotTable.BuiltInStyle = PivotBuiltInStyles.PivotStyleMedium2;

 //Set layout.
 pivotTable.Options.RowLayout = PivotTableRowLayout.Tabular;

 //Set repeat all labels and layout.
 pivotTable.Options.RepeatAllLabels(true);

 //Save workbook.
 workbook.SaveAs("Output.xlsx");
}

Excel chart styles

The appearance of charts can now be quickly changed by just setting the style ID to the chart. Here, the style value must be between 1 and 48.

using (ExcelEngine excelEngine = new ExcelEngine())
{
 //Create worksheet.
 IApplication application = excelEngine.Excel;
 application.DefaultVersion = ExcelVersion.Excel2013;
 IWorkbook workbook = application.Workbooks.Create(1);
 IWorksheet sheet = workbook.Worksheets[0];

 //Add data.
 sheet.Range["A1"].Text = "Jan";
 sheet.Range["B1"].Text = "Feb";
 sheet.Range["C1"].Text = "Mar";
 sheet.Range["A2"].Value = "10";
 sheet.Range["B2"].Value = "20";
 sheet.Range["C2"].Value = "30";

 //Create chart.
 IChart chart = sheet.Charts.Add();

 //Set range.
 chart.DataRange = sheet.Range["A1:C2"];

 //Set Chart Style id from 1 to 48.
 chart.Style = 14;

 //Save.
 workbook.SaveAs("Chart.xlsx");
}

Support to skip blank cells while copying range

XlsIO now allows to skip blank cells while copying data from source range to destination range. That is, if the source range has blank cells, then setting this option to TRUE will skip to copy in the destination range, leaving the destination cells not modified.

using (ExcelEngine excelEngine = new ExcelEngine())
{
 IApplication application = excelEngine.Excel;
 application.DefaultVersion = ExcelVersion.Excel2013;
 IWorkbook workbook = application.Workbooks.Create(1);
 IWorksheet worksheet = workbook.Worksheets[0];

 //Load data.
 worksheet["A1"].Value = "A";
 worksheet["A3"].Value = "B";
 worksheet["A5"].Value = "C";
 worksheet["A7"].Value = "D";
 worksheet["B1"].Value = "E";
 worksheet["B2"].Value = "F";
 worksheet["B4"].Value = "G";
 worksheet["B6"].Value = "H";

 //Apply styles.
 worksheet["A1:A7"].CellStyle.ColorIndex = ExcelKnownColors.Yellow;

 //Skip blank cells while copying.
 worksheet["A1:A7"].CopyTo(worksheet["B1"], ExcelCopyRangeOptions.All, true);

 //Save workbook.
 workbook.SaveAs("SkipBlank.xlsx");
}

Essential DocIO

Word-to-PDF enhancements

Essential DocIO provides the following enhancements in Word-to-PDF conversion:

  • The font embedded with the input DOCX document will be preserved in the resultant PDF document.
  • Editable form fields such as text boxes, check boxes, and drop-downs in the input Word document are converted to their equivalent AcroForm fields in the resultant PDF document.
  • Headings in the input Word document are preserved as PDF bookmarks in the resultant document
  • Input Word document can be converted into a 508-compliant accessible PDF (Tagged PDF) document.

The following code example illustrates setting these properties during Word-to-PDF conversion.

//Loads an existing Word document.
WordDocument wordDocument = new WordDocument("Sample.docx", FormatType.Docx); 
//Creates an instance of the DocToPDFConverter, responsible for Word-to-PDF conversion. 
DocToPDFConverter converter = new DocToPDFConverter(); 
//Sets the PreserveFormFields property as true, to export Word form fields as PDF form fields.
converter.Settings.PreserveFormFields = true; 
//Sets the ExportBookmarks property as Headings, to export Word headings as PDF bookmarks.
converter.Settings.ExportBookmarks = ExportBookmarkType.Headings;
//Sets the AutoTag property as true, to convert Word to PDF by maintaining 508 compliance (accessibility).
converter.Settings.AutoTag = true;
//Converts Word document into PDF document. 
PdfDocument pdfDocument = converter.ConvertToPDF(wordDocument); 
//Closes the WordDocument instance.
wordDocument.Close();
//Saves the PDF file to file system. 
pdfDocument.Save("WordtoPDF.pdf"); 
//Closes the PDF document instance 
pdfDocument.Close(true);
  • Customize font substitution during Word-to-PDF conversion by providing an option to set the alternate font stream.
The following code example illustrates setting font as stream for a font not installed in the machine during Word-to-PDF conversion.
//Loads an existing Word document. 
WordDocument wordDocument = new WordDocument("Sample.docx", FormatType.Docx);
//Hooks the font substitution event.
wordDocument.FontSettings.SubstituteFont += FontSettings_SubstituteFont;
//Creates an instance of the DocToPDFConverter, responsible for Word-to-PDF conversion. 
DocToPDFConverter converter = new DocToPDFConverter();
//Converts Word document into PDF document. 
PdfDocument pdfDocument = converter.ConvertToPDF(wordDocument);
//Unhooks the font substitution event after converting to PDF.
wordDocument.FontSettings.SubstituteFont -= FontSettings_SubstituteFont;
//Closes the WordDocument instance.
wordDocument.Close();
//Saves the PDF file to file system. 
pdfDocument.Save("WordtoPDF.pdf");
//Closes the PDF document instance. 
pdfDocument.Close(true);
private void FontSettings_SubstituteFont(object sender, SubstituteFontEventArgs args)
{
    if (args.OrignalFontName == "Wingdings 2")
        //Sets the alternate font as stream when a specified font is not installed in the production environment.
        args.AlternateFontStream = new FileStream("WINGDNG2.TTF", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
}

Open and save DOCX as ISO 29500 Strict OOXML format

Essential DocIO provides support to open and save DOCX documents compliant with ISO 29500 Strict OOXML format. A new option, StrictDocx, has been added in the FormatType enum.

//Opens the input strict DOCX document
WordDocument document = new WordDocument("Strict.docx", FormatType.StrictDocx);
//Saves the document as strict DOCX
document.Save("Sample.docx", FormatType.StrictDocx);
//Closes the WordDocument instance.
document.Close();

HTML conversion enhancements

The following two enhancements has been added in HTML conversions.

  • Import HTML files in Xamarin platform
  • Added ImageNodeVisited event, which is used to customize image data while importing and exporting HTML files. You can implement logic to upload image to file server and provide the uploaded web path to write within the exported HTML.

The following code example illustrates loading and saving image data in a specific location during import and exporting HTML files.

//Creates a new instance of WordDocument.
WordDocument document = new WordDocument();
//Opens the input HTML document.
document.Open("Input.html", FormatType.Html);
//Hooks the ImageNodeVisited event to write the image to a specific location - absolute/web path.
document.SaveOptions.ImageNodeVisited += SaveImage;
//Saves the document as HTML.
document.Save("Output.html", FormatType.html);
//Unhooks the ImageNodeVisited event after exporting HTML.
document.SaveOptions.ImageNodeVisited -= SaveImage;
//Closes the WordDocument instance.
document.Close();
private void SaveImage(object sender, ImageNodeVisitedEventArgs args)
{
   System.Drawing.Image image = System.Drawing.Image.FromStream(args.ImageStream);
 //Gets the image from stream and saves it to disk.
   image.Save(@"C:/Users/username/Documents/Output_html/img.png");
   //Sets the Uri for the image. It will be written as image source within the exported HTML. 
   args.Uri = @"C:/Users/username/Documents/Output_html/img.png";
   //You can write logic to upload image to file server and provide the uploaded web path to write within the exported HTML.
}

Essential Presentation

Create or edit animation in PowerPoint slide objects

Animations are designed to emphasize objects on a slide and can also control the entrance or exit of objects as the slide is viewed during a slide show.
Essential Presentation provides support for creating and editing animations in a PowerPoint slide. You can create animations with complete control over how and when objects assigned animation effects appear on or exit from the screen.
Essential Presentation supports the major four categories and their subcategories of animations:
  • EntranceAnimate the arrival appearance of an element on a slide.
  • EmphasisDraw attention to an element by changing its size or appearance, or by making it move.
  • ExitAnimate the departure of an element from the slide.
  • Motion PathsMove an element from one location on the slide to another in the specified path.
The key functionalities that can be achieved by Essential Presentation are:
  • Apply animations to text, pictures, shapes, tables, SmartArt graphics, and any object type.
  • Edit the animation in the existing PowerPoint slide.
  • Reorder animations within a slide.
  • Control the timing and duration of an animation and its effects.
  • Apply custom motion paths.
  • Add multiple animations to an object.

An illustration of animation created by Essential Presentation

PowerPoint-to-PDF conversion in Azure

Before, it was not possible to convert PowerPoint to PDF in the Azure environment due to the GDI and Metafile usage. Now, you can convert PowerPoint to PDF in Azure by enabling ‘EnablePortableRendering’ flag as true in the new overload (static) method Convert (IPresentation presentation, bool enablePortableRendering) of PresentationToPdfConverter class.
//Load the PowerPoint presentation to convert.
using(IPresentation presentation = Presentation.Open("Sample.pptx"))
{
    //Initialize 'ChartToImageConverter' to convert charts in the slides.
    presentation.ChartToImageConverter = new ChartToImageConverter();

    //Convert the PowerPoint presentation to PDF.
    using(PdfDocument pdfDocument = PresentationToPdfConverter.Convert(presentation, true))
    {
        //Save the converted PDF document.
        pdfDocument.Save("Sample.pdf");
    }
}

What’s next

Are you interested in trying out these features?
If you’re already a Syncfusion user, please watch out for the new release rolling out by the end of this month. You can download the product setup on Direct-Trac. If you’re not yet a Syncfusion user, you can download a free, 30-day trial.
If you are new to Syncfusion’s file format libraries, we highly recommend that you follow our user guide. To get started quickly with your desired file format, please follow these links:
If you have any questions or require clarification on this feature, please let us know in the comments below. You can also contact us through our support forum or Direct-Trac. We are happy to assist you!

If you like this blog post, we think you’ll also like the following free e-books:

Meet the Author

George Livingston

George Livingston is the Product Manager for PDF at Syncfusion Software. He is passionate about web technologies. He loves creating productive software tools and shooting photographs.