Last active
August 19, 2019 19:55
-
-
Save deanbot/f9aab4b8ee7fe4d20cc4a40e0a664cb1 to your computer and use it in GitHub Desktop.
cs azure function merging pdfs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Text; | |
namespace MyFunction | |
{ | |
public static class MyFunction | |
{ | |
public static async Task<IActionResult> ItsMyFunction () | |
{ | |
// this is needed so that an encoding error is avoided when merging the 2 ca pdfs with PDFSharp | |
// https://gunnarpeipman.com/net/no-data-is-available-for-encoding/ | |
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using PdfSharp.Pdf.IO; | |
using System.IO; | |
using PdfSharp.Pdf; | |
using System.Collections.Generic; | |
namespace MyFunction | |
{ | |
public static class PdfBuilder | |
{ | |
public static byte[] MergePdfs(List<byte[]> pdfs) | |
{ | |
List<PdfDocument> lstDocuments = new List<PdfDocument>(); | |
foreach (var pdf in pdfs) | |
{ | |
lstDocuments.Add(PdfReader.Open(new MemoryStream(pdf), PdfDocumentOpenMode.Import)); | |
} | |
using (PdfDocument outPdf = new PdfDocument()) | |
{ | |
for (int i = 1; i <= lstDocuments.Count; i++) | |
{ | |
foreach (PdfSharp.Pdf.PdfPage page in lstDocuments[i - 1].Pages) | |
{ | |
outPdf.AddPage(page); | |
} | |
} | |
MemoryStream stream = new MemoryStream(); | |
outPdf.Save(stream, false); // this line wll throw an error if encoding not registered | |
byte[] bytes = stream.ToArray(); | |
return bytes; | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Project Sdk="Microsoft.NET.Sdk"> | |
<ItemGroup> | |
<!-- PDFSharp used for merging pdfs--> | |
<!-- <PackageReference Include="PdfSharp" Version="1.51.5185-beta" /> --> | |
<!-- .net standard port of pdfsharp--> | |
<PackageReference Include="PdfSharpNetStandard" Version="0.0.14" /> | |
<!-- required for fixing pdfsharp encoding error --> | |
<PackageReference Include="System.Text.Encoding.CodePages" Version="4.5.1" /> | |
</ItemGroup> | |
</Project> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment