Code: Select all
public ApiResponseModel<InsertWatermarkModel> InsertWatermark(string inputPdf, string watermark, Guid guid)
{
try
{
using (GdPicturePDF pdfGdPicture = new GdPicturePDF())
{
byte[] pdfBytes = Convert.FromBase64String(inputPdf);
byte[] watermarkBytes = Convert.FromBase64String(watermark);
using (MemoryStream inputMemoryStream = new MemoryStream(pdfBytes))
{
pdfGdPicture.LoadFromStream(inputMemoryStream, false);
using (GdPictureImaging imagingGdPicture = new GdPictureImaging())
{
int documentId = imagingGdPicture.CreateGdPictureImageFromByteArray(pdfBytes);
int watermarkId = imagingGdPicture.CreateGdPictureImageFromByteArray(watermarkBytes);
imagingGdPicture.SetTransparency(watermarkId, -128);
float pageWidth = pdfGdPicture.GetPageWidth();
float pageHeight = pdfGdPicture.GetPageHeight();
int watermarkWidth = imagingGdPicture.GetWidth(watermarkId);
int watermarkHeight = imagingGdPicture.GetHeight(watermarkId);
float scaleFactorWidth = pageWidth / watermarkWidth;
float scaleFactorHeight = pageHeight / watermarkHeight;
// Use the smaller scaling factor to fit the entire watermark inside the page
float scaleFactor = Math.Min(scaleFactorWidth, scaleFactorHeight);
// Calculate new dimensions for the watermark
int newWidth = (int)(watermarkWidth * scaleFactor);
int newHeight = (int)(watermarkHeight * scaleFactor);
float xPos = (pageWidth - newWidth) / 2;
float yPos = (pageHeight - newHeight) / 2;
for (int i = 1; i <= pdfGdPicture.GetPageCount(); i++)
{
pdfGdPicture.SelectPage(i);
string imageRes = pdfGdPicture.AddImageFromGdPictureImage(watermarkId, false, false);
pdfGdPicture.DrawImage(imageRes, xPos, yPos, newWidth, newHeight);
}
using (MemoryStream outputMemoryStream = new MemoryStream())
{
pdfGdPicture.SaveToStream(outputMemoryStream);
byte[] outputPdfData = outputMemoryStream.ToArray();
imagingGdPicture.ReleaseGdPictureImage(watermarkId);
return this.CreateApiResponse(new InsertWatermarkModel(Convert.ToBase64String(outputPdfData)), 0, null);
}
}
}
}
}
catch (Exception ex)
{
return this.CreateApiResponse(new InsertWatermarkModel(), 500, ex.Message);
}
}