HomeController.cs
using Bytescout.PDF;
using Bytescout.PDF.Converters;
using System;
using System.Drawing.Printing;
using System.IO;
using System.Web.Mvc;
namespace PDFSDKSamples.Controllers
{
public class HomeController : Controller
{
#region Page Events
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string Operation)
{
switch (Operation)
{
case "Html2PDFConversion":
return _DemonstrateHtml2PDFConversation();
case "TableCreation":
return _DemonstrateTableCreation();
case "SplitPDF":
return _DemonstrateSplitPDF();
case "MergePDF":
return _DemonstrateMergePDF();
case "ProtectingPDF":
return _DemonstrateProtectingPDF();
}
return RedirectToAction("Index");
}
#endregion
#region Event Methods
/// <summary>
/// Demonstrate Html to PDF Conversation
/// </summary>
/// <returns></returns>
private FileResult _DemonstrateHtml2PDFConversation()
{
// HTML to PDF Conversion
using (HtmlToPdfConverter converter = new HtmlToPdfConverter())
{
converter.PageSize = PaperKind.A4;
converter.Orientation = Bytescout.PDF.Converters.PaperOrientation.Portrait;
converter.Footer = "<p style=\"color: blue;\">FOOTER TEXT</p>";
// Get html document in input stream
FileStream inputFileStream = new FileStream(Server.MapPath("~/SampleFiles/sample.html"), FileMode.Open); // Define output stream
MemoryStream outputStream = new MemoryStream();
// Get converted PDF docuement in output stream
converter.ConvertHtmlToPdf(inputFileStream, outputStream);
// Stream back to beginning to allow the data to be read back out
outputStream.Seek(0, SeekOrigin.Begin);
// Return result
return File(outputStream, "text/pdf", "sample_ConvertedFromHTML.pdf");
}
}
/// <summary>
/// Demonstrate PDF Table Creations
/// </summary>
/// <returns></returns>
private FileResult _DemonstrateTableCreation()
{
// Create new document
Document pdfDocument = new Document();
pdfDocument.RegistrationName = "demo";
pdfDocument.RegistrationKey = "demo";
// Add page
Bytescout.PDF.Page page = new Bytescout.PDF.Page(PaperFormat.A4);
pdfDocument.Pages.Add(page);
DeviceColor lightGrayColor = new ColorGray(200);
DeviceColor whiteColor = new ColorGray(255);
DeviceColor lightBlueColor = new ColorRGB(200, 200, 250);
DeviceColor lightRedColor = new ColorRGB(255, 200, 200);
// Create a table and set default background color
Bytescout.PDF.Table table = new Bytescout.PDF.Table();
table.BackgroundColor = lightGrayColor;
// Add row headers column and set its color
table.Columns.Add(new TableColumn("RowHeaders"));
table.Columns[0].BackgroundColor = lightGrayColor;
// Add columns A, B, C, ...
for (int c = 0; c < 10; c++)
{
string columnName = Convert.ToChar('A' + c).ToString();
table.Columns.Add(new TableColumn(columnName, columnName));
}
// Add rows
for (int r = 0; r < 10; r++)
{
// Create new row and set its background color
Bytescout.PDF.TableRow row = table.NewRow();
row.BackgroundColor = whiteColor;
// Set row header text
row["RowHeaders"].Text = (r + 1).ToString();
// Set cell text
for (int c = 0; c < 10; c++)
{
string columnName = Convert.ToChar('A' + c).ToString();
row[columnName].Text = columnName + (r + 1);
}
// Add the row to the table
table.Rows.Add(row);
}
// Decorate the table
table.Rows[1]["B"].BackgroundColor = lightRedColor;
table.Columns[2].BackgroundColor = lightBlueColor;
table.Rows[1].BackgroundColor = lightBlueColor;
table.Rows[1]["RowHeaders"].BackgroundColor = lightBlueColor;
// Draw the table on canvas
page.Canvas.DrawTable(table, 20, 20);
// Save created PDF to memory stream
MemoryStream memoryStream = new MemoryStream();
pdfDocument.Save(memoryStream);
// Stream back to beginning to allow the data to be read back out
memoryStream.Seek(0, SeekOrigin.Begin);
// Return result
return File(memoryStream, "text/pdf", "sample_PDFWithTable.pdf");
}
/// <summary>
/// Demonstrate Split PDF Operation
/// </summary>
/// <returns></returns>
private FileResult _DemonstrateSplitPDF()
{
// Open Document
Document document = new Document(Server.MapPath("~/SampleFiles/sample.pdf"));
document.RegistrationName = "demo";
document.RegistrationKey = "demo";
// Create Split PDF Document
Document documentSplitPDF = new Document();
documentSplitPDF.RegistrationName = "demo";
documentSplitPDF.RegistrationKey = "demo";
// Get page 1&2 to Split PDF document
for (int i = 0; i < 2; i++)
{
documentSplitPDF.Pages.Add(document.Pages[i]);
}
// Save splitted PDF to memory stream
MemoryStream memoryStream = new MemoryStream();
documentSplitPDF.Save(memoryStream);
// Stream back to beginning to allow the data to be read back out
memoryStream.Seek(0, SeekOrigin.Begin);
// Return result
return File(memoryStream, "text/pdf", "sample_splitPDF.pdf");
}
/// <summary>
/// Demonstrate Merge PDF Operation
/// </summary>
/// <returns></returns>
private FileResult _DemonstrateMergePDF()
{
// Open first document
Document document1 = new Document(Server.MapPath("~/SampleFiles/sample.pdf"));
document1.RegistrationName = "demo";
document1.RegistrationKey = "demo";
// Open second document
Document document2 = new Document(Server.MapPath("~/SampleFiles/sample2.pdf"));
document2.RegistrationName = "demo";
document2.RegistrationKey = "demo";
// Add pages from document2 to document1
for (int i = 0; i < document2.Pages.Count; ++i)
{
document1.Pages.Add(document2.Pages[i]);
}
// Save merged PDF to memory stream
MemoryStream memoryStream = new MemoryStream();
document1.Save(memoryStream);
// Stream back to beginning to allow the data to be read back out
memoryStream.Seek(0, SeekOrigin.Begin);
// Return result
return File(memoryStream, "text/pdf", "sample_mergedPDF.pdf");
}
/// <summary>
/// Demonstrate Protecting PDF Operation
/// </summary>
/// <returns></returns>
private FileResult _DemonstrateProtectingPDF()
{
using (Document pdfDocument = new Document())
{
// Set registration key and password
pdfDocument.RegistrationKey = "demo";
pdfDocument.RegistrationName = "demo";
// PDF file path
string pdfFilePath = Server.MapPath("~/SampleFiles/sample.pdf");
// Load pdf file
pdfDocument.Load(pdfFilePath);
// Set document encryption algorythm
pdfDocument.Security.EncryptionAlgorithm = EncryptionAlgorithm.RC4_40bit;
// Set various user permissions
pdfDocument.Security.AllowPrintDocument = false;
pdfDocument.Security.AllowContentExtraction = false;
pdfDocument.Security.AllowModifyAnnotations = false;
pdfDocument.Security.PrintQuality = PrintQuality.LowResolution;
// PDF format supports two kinds of passwords: owner and user password.
// User password allows to view document and perform allowed actions.
// Owner password allows everything, including changing passwords and permissions.
// Set owner password
// pdfDocument.Security.OwnerPassword = "ownerpassword";
// Set user password
pdfDocument.Security.UserPassword = "password1";
// Extract PDF document to Stream
MemoryStream memoryStream = new MemoryStream();
pdfDocument.Save(memoryStream);
// Stream back to beginning to allow the data to be read back out
memoryStream.Seek(0, SeekOrigin.Begin);
// Return result
return File(memoryStream, "text/pdf", "sample_protectedPDF.pdf");
}
}
#endregion
}
}
web.config
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="PDFSDKSamples" />
</namespaces>
</pages>
</system.web.webPages.razor>
<appSettings>
<add key="webpages:Enabled" value="false" />
</appSettings>
<system.webServer>
<handlers>
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
</system.webServer>
<system.web>
<compilation>
<assemblies>
<add assembly="System.Web.Mvc, Version=5.2.4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
</system.web>
</configuration>
Web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
https://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<appSettings>
<add key="webpages:Version" value="3.0.0.0"/>
<add key="webpages:Enabled" value="false"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2"/>
<httpRuntime targetFramework="4.5.2"/>
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-5.2.4.0" newVersion="5.2.4.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.8.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.8.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/>
</compilers>
</system.codedom>
</configuration>
Click here to get your Free Trial version of the SDK
also available as: