I would like to set the an attachment file at the cover sheet of my Pdf portfolio. In my code I have to add doc.Add(new Paragraph("Portable collection"));
otherwise it will show "the document has no page" error. Any idea to have a file at cover sheet instead of having to add new page? Thanks.
My code:
public Stream ExportPortfolio()
{
DateTime dateTime = DateTime.UtcNow.Date;
CreatePortfolio port = new CreatePortfolio();
//dummy files in local
Dictionary<string, FileStream> dict = new Dictionary<string, FileStream>() {
{ "pdf.pdf", File.OpenRead("C:\\training\\pdf.pdf") },
{ "text.txt", File.OpenRead("C:\\training\\text.txt") },
};
WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream";
WebOperationContext.Current.OutgoingResponse.Headers.Add("content-disposition", "inline; filename=" + $"{dateTime.ToString("dd/MM/yyyy")}_portfolio.pdf");
return ManipulatePdf(dict);
}
public Stream ManipulatePdf(Dictionary<string, FileStream> Portfolios)
{
MemoryStream stream = new MemoryStream();
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(stream));
Document doc = new Document(pdfDoc);
doc.Add(new Paragraph("Portable collection"));
PdfCollection collection = new PdfCollection();
collection.SetView(PdfCollection.TILE);
pdfDoc.GetCatalog().SetCollection(collection);
foreach (var item in Portfolios)
{
AddFileAttachment(pdfDoc, item.Value, item.Key);
}
doc.Close();
byte[] file = stream.ToArray();
MemoryStream output = new MemoryStream();
output.Write(file, 0, file.Length);
output.Position = 0;
return output;
}
private void AddFileAttachment(PdfDocument document, FileStream fileStream, string fileName)
{
string embeddedFileName = fileName;
string embeddedFileDescription = fileName;
string fileAttachmentKey = fileName;
PdfFileSpec fileSpec = PdfFileSpec.CreateEmbeddedFileSpec(document, fileStream, embeddedFileDescription,
embeddedFileName, null, null);
document.AddFileAttachment(fileAttachmentKey, fileSpec);
}
What you are missing is the usage of PDFCollection class. You can use it to set the initial document property for the cover page in the ManipulatePDF method/function in your code above.
PdfCollection collection = new PdfCollection();
collection.SetView(PdfCollection.TILE);
pdfDoc.GetCatalog().SetCollection(collection);
collection.SetInitialDocument("");
This should help with setting the first page of the PDF as cover page for PDF portfolio.