Modify an Existing PDF
Opens an existing PDF document, adds a logo to its first page and a watermark (a template with text and an image) repeated on every page, then saves it as a new file.
C# code of this sample
using System;
using System.ComponentModel.DataAnnotations;
using System.Drawing;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using ExpertPdf.PdfCreator;
namespace ExpertPdf.PdfCreator.Samples.Pages
{
public class ModifyExistingPdfDemoModel : PageModel
{
[BindProperty, DisplayFormat(ConvertEmptyStringToNull = false)]
public string PdfFile { get => _PdfFile; set => _PdfFile = Helper.HostedSampleFile(value); }
private string _PdfFile = Path.Combine(Helper.FilesFolder, "sample.pdf");
[BindProperty, DisplayFormat(ConvertEmptyStringToNull = false)]
public string Watermark { get; set; } = "CONFIDENTIAL";
public string Message { get; set; }
public void OnGet()
{
}
public IActionResult OnPost()
{
try
{
return File(CreatePdf(), "application/pdf", "Modified.pdf");
}
catch (Exception ex)
{
Message = "The PDF document was not created. " + ex.Message;
return Page();
}
}
private byte[] CreatePdf()
{
// LicensingManager.LicenseKey = "your license key";
string logoFile = Path.Combine(Helper.FilesFolder, @"img\logo.jpg");
// open the existing document; it keeps the file open until Close
Document document = new Document(PdfFile.Trim());
try
{
// a logo with a border on the first page
PdfPage firstPage = document.Pages[0];
AddElementResult result = firstPage.AddElement(new ImageElement(0, 0, 120, logoFile));
firstPage.AddElement(new RectangleElement(0, 0, result.EndPageBounds.Width, result.EndPageBounds.Height));
// a watermark: a template is drawn on every page of the document, the existing pages included
float width = 300, height = 110;
float x = (firstPage.ClientRectangle.Width - width) / 2;
float y = (firstPage.ClientRectangle.Height - height) / 2;
Template watermark = document.AddTemplate(new RectangleF(x, y, width, height));
PdfFont font = document.AddFont(StdFontBaseFamily.HelveticaBold);
font.Size = 36;
TextElement text = new TextElement(0, 0, width, Watermark, font);
text.TextAlign = HorizontalTextAlign.Center;
text.ForeColor = Color.Red;
text.Transparency = 30;
watermark.AddElement(text);
ImageElement image = new ImageElement((width - 200) / 2, 50, 200, logoFile);
image.Transparency = 30;
watermark.AddElement(image);
return document.Save();
}
finally
{
document.Close();
}
}
}
}