using Aspose.Pdf.Facades;
using Aspose.Pdf.Text;
using Aspose.Pdf.Drawing;
using System.Security.Cryptography;
using System.Text;
using Aspose.Pdf;
namespace OSHD_Intranet.Classes.Common.Utilities
{
public class PdfDocument
{
public string UserPasscode;
public string OwnerPasscode;
public byte[] Content;
public bool HasValue = false;
}
public class Base64Document
{
public string Content;
public decimal xaxis = 0;
public decimal yaxis = 0;
public int pageno = 0;
}
public class PdfHelper
{
public const int PASSCODE_LENGTH = 12;
public const string PDF_FONT_FOLDER = "usr/share/fonts/truetype/msttcorefonts";
public PdfDocument GeneratePdf(StringBuilder contentSB, string pdfTitle = "", bool showstamp = true, bool passcodeProtect = false)
{
PdfDocument pdfDocument = null;
try
{
// Load license
try
{
Aspose.Pdf.License license = new Aspose.Pdf.License();
license.SetLicense("Aspose.Total.NET.lic");
}
catch (Exception e)
{
var il = LoggerFactory.Create(builder => { builder.AddConsole(); });
ILogger logger = il.CreateLogger("OSHD_Internet");
logger.LogError(e.ToString());
}
using var stream1 = new MemoryStream(Encoding.UTF8.GetBytes(contentSB.ToString()));
FontRepository.Sources.Add(new Aspose.Pdf.Text.FolderFontSource(PdfHelper.PDF_FONT_FOLDER));
HtmlLoadOptions loadOptions = new HtmlLoadOptions();
loadOptions.PageInfo.Margin.Top = (1.25) * 28.3465;
loadOptions.PageInfo.Margin.Bottom = (1.25) * 28.3465;
loadOptions.PageInfo.Margin.Left = (1.75) * 28.3465;
loadOptions.PageInfo.Margin.Right = (1.75) * 28.3465;
loadOptions.PageInfo.Height = PageSize.A4.Height;
loadOptions.PageInfo.Width = PageSize.A4.Width;
Document document = new Document(stream1, loadOptions);
document.Info.Title = pdfTitle;
if (showstamp)
{
//Print header
if (!string.IsNullOrWhiteSpace(pdfTitle))
{
TextStamp headerTextStamp = new TextStamp(pdfTitle)
{
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
TopMargin = 25,
LeftMargin = 50,
};
headerTextStamp.TextState.FontSize = 8.0F;
headerTextStamp.TextState.FontStyle = FontStyles.Bold;
headerTextStamp.TextState.ForegroundColor = Color.Black;
foreach (Page page in document.Pages)
{
page.AddStamp(headerTextStamp);
}
}
}
DocumentPrivilege privilege = DocumentPrivilege.ForbidAll;
privilege.AllowPrint = true;
privilege.AllowScreenReaders = true;
PdfFileSecurity fileSecurity = new PdfFileSecurity(document);
fileSecurity.SetPrivilege(privilege);
// Print footer (paging)
//if (showPaging)
//{
// document.ProcessParagraphs();
// TextStamp footerTextStamp = new TextStamp(string.Empty)
// {
// HorizontalAlignment = HorizontalAlignment.Center,
// VerticalAlignment = VerticalAlignment.Bottom,
// BottomMargin = 20
// };
// footerTextStamp.TextState.ForegroundColor = Color.Gray;
// foreach (Page page in document.Pages)
// {
// footerTextStamp.Value = $"Page {page.Number} of {document.Pages.Count}";
// page.AddStamp(footerTextStamp);
// }
//}
pdfDocument = new PdfDocument();
using var stream2 = new MemoryStream();
document.Save(stream2);
pdfDocument.HasValue = true;
if (passcodeProtect)
{
// In encrypted pdf, hyperlinks are not clickable (this is an ASPOSE issue)
// To workaround, save the original document in stream first and create a new encrypted document from this stream
using var stream3 = new MemoryStream();
pdfDocument.UserPasscode = GenerateRandomString(PdfHelper.PASSCODE_LENGTH);
pdfDocument.OwnerPasscode = GenerateRandomString(PdfHelper.PASSCODE_LENGTH); // this is not used, but we will still generate
Document encryptedDoc = new Document(stream2);
encryptedDoc.Encrypt(pdfDocument.UserPasscode, pdfDocument.OwnerPasscode, DocumentPrivilege.ScreenReaders, CryptoAlgorithm.AESx256, false);
encryptedDoc.Save(stream3);
pdfDocument.Content = stream3.ToArray();
}
else
{
pdfDocument.Content = stream2.ToArray();
}
}
catch (Exception e)
{
var il = LoggerFactory.Create(builder => { builder.AddConsole(); });
ILogger logger = il.CreateLogger("OSHD_Intranet");
logger.LogError(e.ToString());
}
return pdfDocument;
}
public PdfDocument GenerateLetterPdf(StringBuilder contentSB, string pdfTitle = "", bool showstamp = true, bool passcodeProtect = false, double topMargin = (1.25) * 28.3465)
{
PdfDocument pdfDocument = null;
try
{
// Load license
try
{
Aspose.Pdf.License license = new Aspose.Pdf.License();
license.SetLicense("Aspose.Total.NET.lic");
}
catch (Exception e)
{
var il = LoggerFactory.Create(builder => { builder.AddConsole(); });
ILogger logger = il.CreateLogger("OSHD_Internet");
logger.LogError(e.ToString());
}
TextFormattingOptions textOptions = new TextFormattingOptions();
textOptions.WrapMode = TextFormattingOptions.WordWrapMode.ByWords;
//HtmlFragment textFragment = new HtmlFragment(contentSB.ToString());
using var stream1 = new MemoryStream(Encoding.UTF8.GetBytes(contentSB.ToString()));
FontRepository.Sources.Add(new Aspose.Pdf.Text.FolderFontSource(PdfHelper.PDF_FONT_FOLDER));
HtmlLoadOptions loadOptions = new HtmlLoadOptions();
loadOptions.PageInfo.Margin.Top = topMargin;
loadOptions.PageInfo.Margin.Bottom = topMargin;
loadOptions.PageInfo.Margin.Left = (1.75) * 18.3465;
loadOptions.PageInfo.Margin.Right = (1.75) * 18.3465;
loadOptions.PageInfo.Height = PageSize.A4.Height;
loadOptions.PageInfo.Width = PageSize.A4.Width;
Document document = new Document(stream1, loadOptions);
//document.Pages[1].Paragraphs.Add(textFragment);
document.Info.Title = pdfTitle;
if (showstamp)
{
//Print header
if (!string.IsNullOrEmpty(pdfTitle))
{
TextStamp headerTextStamp = new TextStamp(pdfTitle)
{
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
TopMargin = 25,
LeftMargin = 50,
};
headerTextStamp.TextState.FontSize = 8.0F;
headerTextStamp.TextState.FontStyle = FontStyles.Bold;
headerTextStamp.TextState.ForegroundColor = Color.Black;
foreach (Page page in document.Pages)
{
page.AddStamp(headerTextStamp);
}
}
}
DocumentPrivilege privilege = DocumentPrivilege.ForbidAll;
privilege.AllowPrint = true;
privilege.AllowScreenReaders = true;
PdfFileSecurity fileSecurity = new PdfFileSecurity(document);
fileSecurity.SetPrivilege(privilege);
// Print footer (paging)
//if (showPaging)
//{
// document.ProcessParagraphs();
// TextStamp footerTextStamp = new TextStamp(string.Empty)
// {
// HorizontalAlignment = HorizontalAlignment.Center,
// VerticalAlignment = VerticalAlignment.Bottom,
// BottomMargin = 20
// };
// footerTextStamp.TextState.ForegroundColor = Color.Gray;
// foreach (Page page in document.Pages)
// {
// footerTextStamp.Value = $"Page {page.Number} of {document.Pages.Count}";
// page.AddStamp(footerTextStamp);
// }
//}
pdfDocument = new PdfDocument();
using var stream2 = new MemoryStream();
document.Save(stream2);
pdfDocument.HasValue = true;
if (passcodeProtect)
{
// In encrypted pdf, hyperlinks are not clickable (this is an ASPOSE issue)
// To workaround, save the original document in stream first and create a new encrypted document from this stream
using var stream3 = new MemoryStream();
pdfDocument.UserPasscode = GenerateRandomString(PdfHelper.PASSCODE_LENGTH);
pdfDocument.OwnerPasscode = GenerateRandomString(PdfHelper.PASSCODE_LENGTH); // this is not used, but we will still generate
Document encryptedDoc = new Document(stream2);
encryptedDoc.Encrypt(pdfDocument.UserPasscode, pdfDocument.OwnerPasscode, DocumentPrivilege.ScreenReaders, CryptoAlgorithm.AESx256, false);
encryptedDoc.Save(stream3);
pdfDocument.Content = stream3.ToArray();
}
else
{
pdfDocument.Content = stream2.ToArray();
}
}
catch (Exception e)
{
var il = LoggerFactory.Create(builder => { builder.AddConsole(); });
ILogger logger = il.CreateLogger("OSHD_Intranet");
logger.LogError(e.ToString());
}
return pdfDocument;
}
public static string GenerateRandomString(int length)
{
char[] charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
try
{
byte[] data = new byte[4 * length];
using (var crypto = RandomNumberGenerator.Create())
{
crypto.GetBytes(data);
}
StringBuilder result = new StringBuilder(length);
for (int i = 0; i < length; i++)
{
var rnd = BitConverter.ToUInt32(data, i * 4);
var idx = rnd % charset.Length;
result.Append(charset[idx]);
}
return result.ToString();
}
catch (Exception e)
{
var il = LoggerFactory.Create(builder => { builder.AddConsole(); });
ILogger logger = il.CreateLogger("OSHD_Intranet");
logger.LogError(e.ToString());
}
return string.Empty;
}
public static void InitializeAspose()
{
License license = new License();
license.SetLicense("Aspose.Total.NET.lic");
string pdf_fonts_folder = "usr/share/fonts/truetype/msttcorefonts";
Aspose.Pdf.Text.FontRepository.Sources.Add(new Aspose.Pdf.Text.FolderFontSource(pdf_fonts_folder));
using var stream1 = new MemoryStream(Encoding.UTF8.GetBytes("Initializing Aspose PDF"));
HtmlLoadOptions loadOptions = new HtmlLoadOptions();
Document document = new Document(stream1, loadOptions);
}
}
}
This is my code, I faced error below when host in docker linux OS:
{System.PlatformNotSupportedException: System.Drawing.Common is not supported on this platform.
at System.Drawing.Drawing2D.Matrix…ctor(Single m11, Single m12, Single m21, Single m22, Single dx, Single dy)
at #=zjBUsORi2vRbxKae$hipe7_yndd1crLQhsw==.#=zSQk4fZEOoQf2gZrTUUorSl4=(SizeF #=zxCU6SUE=)
at #=zjBUsORi2vRbxKae$hipe7_yndd1crLQhsw==.#=znUJpZK0=(SizeF #=zxCU6SUE=)
at #=zWD2j2Ft8sKhO3xRH6YlHpgpKVPkxicsZ1Q==.Render(#=zzeyKQQQpvUirV3a2DneaSPjVlNnv #=zgLT9OHk=, CancellationToken #=zMv6IMy0=)
at #=zepXMn3aOXQeGsBRvP55jJ$cWVANrsfMbCQ==.#=zZl25FXfgTxY$(#=z025FSXRaPSKzTVLLTpLUP$4= #=zOCpCAhUczVPnAE511A==, #=zzJKQrO2_JkadMqH_MPB9rx6XknqP[] #=zTrUZTFPEiGD0, #=zzeyKQQQpvUirV3a2DneaSPjVlNnv #=zgLT9OHk=, CancellationToken #=zEqeoIz0=)
at #=zCuETAWWVHwf8kYlsKKx7zulCAckO.Render(#=zzeyKQQQpvUirV3a2DneaSPjVlNnv #=zgLT9OHk=, CancellationToken #=zEqeoIz0=, #=zIH1bQDzVlZBVGEwqoUJJGcE=[] #=z5eiBLFk=, #=zdx8OitpyrXOgSNmhMFQByWg=[] #=zMmjcrAc=)
at #=zCuETAWWVHwf8kYlsKKx7zulCAckO.Render(#=zzeyKQQQpvUirV3a2DneaSPjVlNnv #=zgLT9OHk=, TimeSpan #=zBEHWQ0Q=, #=zxzNMWNI$pHHo_y2wAQaogY8=[] #=zDwl1kFk=)
at #=zu49guH3YXX6Fo4kaMZO30c8zSGyX.Render(#=zzeyKQQQpvUirV3a2DneaSPjVlNnv #=zgLT9OHk=, #=zvcYVrxc= #=zKIcLiRU=, TimeSpan #=zBEHWQ0Q=)
at #=zu49guH3YXX6Fo4kaMZO30c8zSGyX.Render(#=zzeyKQQQpvUirV3a2DneaSPjVlNnv #=zgLT9OHk=, #=zvcYVrxc= #=zKIcLiRU=)
at #=zd5KiagU$TAnvgbzDPxEB4x$cJD0o.#=zTNRvK7r7MOD1(Stream #=zoXOz2yS3ECC_, Document #=zYvD5hMHeEEwt, HtmlLoadOptions #=z35bYqiWebbIo, String #=zgW4WiFY59QIX)
at #=zd5KiagU$TAnvgbzDPxEB4x$cJD0o.#=zb425bcY=(Stream #=zoXOz2yS3ECC_, Document #=zYvD5hMHeEEwt, HtmlLoadOptions #=z35bYqiWebbIo, String #=zgW4WiFY59QIX)
at #=zd5KiagU$TAnvgbzDPxEB4x$cJD0o.#=zb425bcY=(Stream #=zoXOz2yS3ECC_, Document #=zYvD5hMHeEEwt, HtmlLoadOptions #=z35bYqiWebbIo)
at Aspose.Pdf.Document.#=zLvLiNJQ=(Stream #=zCv_6Bi0=, LoadOptions #=z7rDPLZI=)
at Aspose.Pdf.Document…ctor(Stream input, LoadOptions options)
at OSHD_Intranet.Classes.Common.Utilities.PdfHelper.InitializeAspose()
Please kindly assist.
Thanks.