public bool AddWaterMarkerToPdf(string pdfFile, string destFile, string text, string fontFamily, string fontColor, int fontSize = 50) { if (File.Exists(pdfFile)) { try { using (var pr = new PdfReader(pdfFile)) { var rgbColor = System.Drawing.ColorTranslator.FromHtml(fontColor); PdfFont font = fontFamily.Contains("STSong") ? PdfFontFactory.CreateFont(fontFamily, "UniGB-UCS2-H", true) : PdfFontFactory.CreateFont(fontFamily);//PdfFontFactory.CreateFont(fontFamily, "UniGB-UCS2-H", true); if (font != null) { var textLength = font.GetWidth(text, fontSize); var pw = new PdfWriter(destFile); var pdfDoc = new PdfDocument(pr, pw); Rectangle ps; PdfCanvas canvas; var pageCount = pdfDoc.GetNumberOfPages(); for (var i = 1; i < pageCount + 1; i++) { var page = pdfDoc.GetPage(i); ps = page.GetPageSize(); float watermarkTrimmingRectangleWidth = textLength; //Math.Min(ps.GetWidth(), ps.GetHeight()); float watermarkTrimmingRectangleHeight = watermarkTrimmingRectangleWidth; var rotationInRads = MathF.Atan2(ps.GetHeight(), ps.GetWidth()); //var angle = rotationInRads * 180f / MathF.PI; float formWidth = ps.GetWidth(); //watermarkTrimmingRectangleWidth; float formHeight = ps.GetHeight(); //watermarkTrimmingRectangleWidth; float formXOffset = 0; float formYOffset = 0; float xTranslation = (formWidth - watermarkTrimmingRectangleWidth * MathF.Cos(rotationInRads)) / 2; float yTranslation = (formHeight - watermarkTrimmingRectangleWidth * MathF.Sin(rotationInRads)) / 2; //Center the annotation Rectangle watermarkTrimmingRectangle = new Rectangle(0, 0, formWidth, formHeight);//watermarkTrimmingRectangleWidth, watermarkTrimmingRectangleWidth); PdfWatermarkAnnotation watermark = new PdfWatermarkAnnotation(watermarkTrimmingRectangle); //Apply linear algebra rotation math //Create identity matrix AffineTransform transform = new AffineTransform(); //No-args constructor creates the identity transform //Apply translation //transform.Translate(xTranslation, yTranslation); //Apply rotation transform.Translate(xTranslation, yTranslation); transform.Rotate(rotationInRads); PdfFixedPrint fixedPrint = new PdfFixedPrint(); watermark.SetFixedPrint(fixedPrint); //Create appearance Rectangle formRectangle = new Rectangle(formXOffset, formYOffset, formWidth, formHeight); //Observation: font XObject will be resized to fit inside the watermark rectangle PdfFormXObject form = new PdfFormXObject(formRectangle); PdfExtGState gs1 = new PdfExtGState().SetFillOpacity(rgbColor.A / 255f); canvas = new PdfCanvas(form, pdfDoc); float[] transformValues = new float[6]; transform.GetMatrix(transformValues); canvas.SaveState() .BeginText().SetFillColorRgb(rgbColor.R / 225f, rgbColor.G / 225f, rgbColor.B / 255f).SetExtGState(gs1) .SetTextMatrix(transformValues[0], transformValues[1], transformValues[2], transformValues[3], transformValues[4], transformValues[5]) .SetFontAndSize(font, fontSize) .ShowText(text) .EndText() .RestoreState(); canvas.Release(); watermark.SetAppearance(PdfName.N, new PdfAnnotationAppearance(form.GetPdfObject())); watermark.SetFlags(PdfAnnotation.PRINT); page.AddAnnotation(watermark); } pdfDoc.Close(); } else { App.Current.Dispatcher.Invoke(() => { MessageBoxX.Show($"没有找到字体{fontFamily},请确认已安装", "字体错误"); }); return(false); } return(true); } } catch (Exception ex) { Analytics.TrackEvent("PDFError", new Dictionary <string, string> { ["message"] = ex.ToString() }); } finally { File.Delete(pdfFile); } } return(false); }
/// <summary> /// Watermarks a PDF file. /// </summary> /// <paramref name="fileName"/> private void WatermarkPdf(string fileName) { var watermarkText = _operation.WatermarkText; var sourceFile = $"{_operation.SourcePath}\\{fileName}"; var destinationPath = $"{_operation.DestinationPath}\\{PathWatermarked}"; var destinationFile = $"{destinationPath}\\{fileName}"; ValidatePath(destinationPath); const float watermarkTrimmingRectangleWidth = 600; const float watermarkTrimmingRectangleHeight = 600; const float formWidth = 300; const float formHeight = 300; const float formXOffset = 0; const float formYOffset = 0; const float xTranslation = 50; const float yTranslation = 25; const double rotationInRads = Math.PI / 3; try { FontCache.ClearSavedFonts(); } catch (Exception exception) { Log.Error(exception.Message); } var font = PdfFontFactory.CreateFont(StandardFonts.COURIER); const float fontSize = 119; using var reader = new PdfReader(new MemoryStream(File.ReadAllBytes(sourceFile))); using var pdfDoc = new PdfDocument(reader, new PdfWriter(destinationFile)); var numberOfPages = pdfDoc.GetNumberOfPages(); PdfPage page = null; for (var i = 1; i <= numberOfPages; i++) { page = pdfDoc.GetPage(i); var ps = page.GetPageSize(); //Center the annotation var bottomLeftX = ps.GetWidth() / 2 - watermarkTrimmingRectangleWidth / 2; var bottomLeftY = ps.GetHeight() / 2 - watermarkTrimmingRectangleHeight / 2; var watermarkTrimmingRectangle = new Rectangle(bottomLeftX, bottomLeftY, watermarkTrimmingRectangleWidth, watermarkTrimmingRectangleHeight); var watermark = new PdfWatermarkAnnotation(watermarkTrimmingRectangle); //Apply linear algebra rotation math //Create identity matrix var transform = new AffineTransform(); //No-args constructor creates the identity transform //Apply translation transform.Translate(xTranslation, yTranslation); //Apply rotation transform.Rotate(rotationInRads); var fixedPrint = new PdfFixedPrint(); watermark.SetFixedPrint(fixedPrint); //Create appearance var formRectangle = new Rectangle(formXOffset, formYOffset, formWidth, formHeight); //Observation: font XObject will be resized to fit inside the watermark rectangle var form = new PdfFormXObject(formRectangle); var gs1 = new PdfExtGState().SetFillOpacity(0.6f); var canvas = new PdfCanvas(form, pdfDoc); var transformValues = new float[6]; transform.GetMatrix(transformValues); canvas.SaveState() .BeginText().SetColor(ColorConstants.GRAY, true).SetExtGState(gs1) .SetTextMatrix(transformValues[0], transformValues[1], transformValues[2], transformValues[3], transformValues[4], transformValues[5]) .SetFontAndSize(font, fontSize) .ShowText(watermarkText) .EndText() .RestoreState(); canvas.Release(); watermark.SetAppearance(PdfName.N, new PdfAnnotationAppearance(form.GetPdfObject())); watermark.SetFlags(PdfAnnotation.PRINT); page.AddAnnotation(watermark); } page?.Flush(); pdfDoc.Close(); }
public byte[] Add(string infile, string outFile) { PdfFont baseFont = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD, Encoding.ASCII.EncodingName, false); Rectangle pageSize; string NoOfPagesPadded = string.Empty; string PageNoPadded = string.Empty; string HdrLeft = string.Empty; string HdrRight = string.Empty; int xLeft = 30; int xRight = 110; //was 100 int xTop = 30; float watermarkTrimmingRectangleWidth; //= 300; float watermarkTrimmingRectangleHeight = 300; float formXOffset = 0; float formYOffset = -5; // was zero set to -5 because dangling letters (e.g. g) were being cut-off byte[] outByteFile; byte[] inByteFile = null; try { inByteFile = File.ReadAllBytes(infile); IRandomAccessSource inSourceFile = new RandomAccessSourceFactory().CreateSource(inByteFile); using (PdfReader reader = new PdfReader(inSourceFile, new ReaderProperties()).SetUnethicalReading(true)) { using (var outMemoryFile = new MemoryStream()) { using (PdfWriter pdfWrite = new PdfWriter(outMemoryFile)) { using (PdfDocument pdfDoc = new PdfDocument(reader, pdfWrite)) { using (Document doc = new Document(pdfDoc)) { int n = pdfDoc.GetNumberOfPages(); for (var i = 1; i <= n; i++) { // Remove annotation if it exists PdfDictionary pageDict = pdfDoc.GetPage(i).GetPdfObject(); PdfArray annots = pageDict.GetAsArray(PdfName.Annots); if (annots != null) { for (int j = 0; j < annots.Size(); j++) { PdfDictionary annotation = annots.GetAsDictionary(j); if (PdfName.Watermark.Equals(annotation.GetAsName(PdfName.Subtype))) { string NMvalue = annotation.GetAsString(PdfName.NM).GetValue(); if (NMvalue == AnnotName) { annotation.Clear(); } } } } } for (int i = 1; i <= n; i++) { PdfPage page = pdfDoc.GetPage(i); pageSize = page.GetMediaBox(); watermarkTrimmingRectangleWidth = pageSize.GetWidth(); float PageWidth = pageSize.GetWidth(); float PageHeight = pageSize.GetHeight(); int rotation = page.GetRotation(); Rectangle watermarkTrimmingRectangle = new Rectangle(pageSize.GetLeft() + xLeft, pageSize.GetTop() - xTop, watermarkTrimmingRectangleWidth, watermarkTrimmingRectangleHeight); PdfWatermarkAnnotation watermark = new PdfWatermarkAnnotation(watermarkTrimmingRectangle); watermark.SetName(new PdfString(AnnotName)); Rectangle formRectangle = new Rectangle(formXOffset, formYOffset, watermarkTrimmingRectangleWidth, watermarkTrimmingRectangleHeight); PdfFormXObject form = new PdfFormXObject(formRectangle); //Observation: font XObject will be resized to fit inside the watermark rectangle. If it is larger, your text will be stretched. PdfCanvas canvasOver = new PdfCanvas(form, pdfDoc); canvasOver.SetFillColor(iText.Kernel.Colors.ColorConstants.RED); canvasOver.SetFontAndSize(baseFont, 10); canvasOver.SaveState(); string SDSNo = "z2345678"; HdrLeft = CompanyName + $" SDS# {SDSNo}"; // HdrLeft = $"PWidth: {PageWidth.ToString()} rotation: {rotation.ToString()}"; //qqtempqq NoOfPagesPadded = (n.ToString()); PageNoPadded = i.ToString(); HdrRight = $"Page {PageNoPadded} of {NoOfPagesPadded}"; // HdrRight = $"PHeight: {PageHeight.ToString()}"; //qqtempqq canvasOver.BeginText() .SetColor(iText.Kernel.Colors.ColorConstants.RED, true) .SetFontAndSize(baseFont, 10) .ShowText(HdrLeft) .EndText(); canvasOver.BeginText() .MoveText(formRectangle.GetRight() - xRight, 0) .SetColor(iText.Kernel.Colors.ColorConstants.RED, true) .SetFontAndSize(baseFont, 10) .ShowText(HdrRight) .EndText(); canvasOver.SaveState(); canvasOver.RestoreState(); canvasOver.Release(); watermark.SetAppearance(PdfName.N, new PdfAnnotationAppearance(form.GetPdfObject())); watermark.SetFlags(PdfAnnotation.PRINT); page.AddAnnotation(watermark); } } } outByteFile = outMemoryFile.ToArray(); } } } File.WriteAllBytes(outFile, outByteFile); } catch (Exception ex) { Console.WriteLine("Error:" + ex.ToString()); return(inByteFile); throw; } return(outByteFile); }
public void SetAnnotation() { _watermark.SetAppearance(PdfName.N, new PdfAnnotationAppearance(_form.GetPdfObject())); _watermark.SetFlags(PdfAnnotation.PRINT); }