public void SetText(Color color, string text, Font font) { float[] transformValues = new float[6]; _transform.GetMatrix(transformValues); _canvas.WriteText(color, transformValues, font, text); }
private void ApplyConcatMatrix(DrawContext drawContext, float?angle) { AffineTransform rotationTransform = AffineTransform.GetRotateInstance((float)angle); Rectangle rect = GetBorderAreaBBox(); IList <Point> rotatedPoints = TransformPoints(RectangleToPointsList(rect), rotationTransform); float[] shift = CalculateShiftToPositionBBoxOfPointsAt(rect.GetX(), rect.GetY() + rect.GetHeight(), rotatedPoints ); double[] matrix = new double[6]; rotationTransform.GetMatrix(matrix); drawContext.GetCanvas().ConcatMatrix(matrix[0], matrix[1], matrix[2], matrix[3], shift[0], shift[1]); }
/// <summary> /// Builds the /// <see cref="iText.Kernel.Colors.Color"/> /// object representing the linear gradient with specified configuration /// that fills the target bounding box. /// </summary> /// <param name="targetBoundingBox">the bounding box to be filled in current space</param> /// <param name="contextTransform"> /// the transformation from the base coordinates space into /// the current space. The /// <see langword="null"/> /// value is valid and can be used /// if there is no transformation from base coordinates to current space /// specified, or it is equal to identity transformation. /// </param> /// <param name="document"> /// the /// <see cref="iText.Kernel.Pdf.PdfDocument"/> /// for which the linear gradient would be built. /// </param> /// <returns> /// the constructed /// <see cref="iText.Kernel.Colors.Color"/> /// or /// <see langword="null"/> /// if no color to be applied /// or base gradient vector has been specified /// </returns> public virtual Color BuildColor(Rectangle targetBoundingBox, AffineTransform contextTransform, PdfDocument document) { // TODO: DEVSIX-4136 the document argument would be required for opaque gradients (as we would need to create a mask form xObject) Point[] baseCoordinatesVector = GetGradientVector(targetBoundingBox, contextTransform); if (baseCoordinatesVector == null || this.stops.IsEmpty()) { // Can not create gradient color with 0 stops or null coordinates vector return(null); } // evaluate actual coordinates and transformation AffineTransform shadingTransform = new AffineTransform(); if (contextTransform != null) { shadingTransform.Concatenate(contextTransform); } AffineTransform gradientTransformation = GetCurrentSpaceToGradientVectorSpaceTransformation(targetBoundingBox , contextTransform); if (gradientTransformation != null) { try { if (targetBoundingBox != null) { targetBoundingBox = Rectangle.CalculateBBox(JavaUtil.ArraysAsList(gradientTransformation.InverseTransform( new Point(targetBoundingBox.GetLeft(), targetBoundingBox.GetBottom()), null), gradientTransformation.InverseTransform (new Point(targetBoundingBox.GetLeft(), targetBoundingBox.GetTop()), null), gradientTransformation.InverseTransform (new Point(targetBoundingBox.GetRight(), targetBoundingBox.GetBottom()), null), gradientTransformation .InverseTransform(new Point(targetBoundingBox.GetRight(), targetBoundingBox.GetTop()), null))); } shadingTransform.Concatenate(gradientTransformation); } catch (NoninvertibleTransformException) { LogManager.GetLogger(GetType()).Error(iText.IO.LogMessageConstant.UNABLE_TO_INVERT_GRADIENT_TRANSFORMATION ); } } PdfShading.Axial axial = CreateAxialShading(baseCoordinatesVector, this.stops, this.spreadMethod, targetBoundingBox ); if (axial == null) { return(null); } PdfPattern.Shading shading = new PdfPattern.Shading(axial); if (!shadingTransform.IsIdentity()) { double[] matrix = new double[6]; shadingTransform.GetMatrix(matrix); shading.SetMatrix(new PdfArray(matrix)); } return(new PatternColor(shading)); }
public static Transform AsTransform(this AffineTransform transform) { if (transform.IsIdentity) { return(Transform.Identity); } var values = new float[6]; transform.GetMatrix(values); return(new MatrixTransform(values[0], values[1], values[2], values[3], values[4], values[5])); }
private void TranslateImage(float xDistance, float yDistance, AffineTransform t) { t.Translate(xDistance, yDistance); t.GetMatrix(matrix); if (fixedXPosition != null) { fixedXPosition += (float)t.GetTranslateX(); } if (fixedYPosition != null) { fixedYPosition += (float)t.GetTranslateY(); } }
private void GetMatrix(AffineTransform t, float imageItselfScaledWidth, float imageItselfScaledHeight) { t.GetMatrix(matrix); PdfXObject xObject = ((Image)(GetModelElement())).GetXObject(); if (xObject is PdfImageXObject) { matrix[0] *= imageItselfScaledWidth; matrix[1] *= imageItselfScaledWidth; matrix[2] *= imageItselfScaledHeight; matrix[3] *= imageItselfScaledHeight; } }
/// <exception cref="System.IO.IOException"/> private static TextRenderInfo InitTRI(String text, double angle) { CanvasGraphicsState gs = new CanvasGraphicsState(); gs.SetFont(PdfFontFactory.CreateFont()); gs.SetFontSize(12); float[] matrix = new float[6]; AffineTransform transform = AffineTransform.GetRotateInstance(angle); transform.GetMatrix(matrix); return(new TextRenderInfo(new PdfString(text), gs, new Matrix(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]), new Stack <CanvasTag>())); }
public static Matrix AsMatrix(this AffineTransform transform) { var values = new float[9]; transform.GetMatrix(values); values[Matrix.Mpersp0] = 0; // 6 values[Matrix.Mpersp1] = 0; // 7 values[Matrix.Mpersp2] = 1; // 8 var matrix = new Matrix(); matrix.SetValues(values); return(matrix); }
public static CGAffineTransform AsCGAffineTransform(this AffineTransform transform) { if (transform != null) { var matrix = new float[6]; transform.GetMatrix(matrix); float xx = matrix[0]; float yx = matrix[1]; float xy = matrix[2]; float yy = matrix[3]; float x0 = matrix[4]; float y0 = matrix[5]; return(new CGAffineTransform(xx, yx, xy, yy, x0, y0)); } return(CGAffineTransform.MakeIdentity()); }
protected void ManipulatePdf(String dest) { PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest)); ImageData image = ImageDataFactory.Create(IMG); // Translation defines the position of the image on the page and scale transformation sets image dimensions // Please also note that image without scaling is drawn in 1x1 rectangle. And here we draw image on page using // its original size in pixels. AffineTransform affineTransform = AffineTransform.GetTranslateInstance(36, 300); // Make sure that the image is visible by concatenating a scale transformation affineTransform.Concatenate(AffineTransform.GetScaleInstance(image.GetWidth(), image.GetHeight())); PdfCanvas canvas = new PdfCanvas(pdfDoc.GetFirstPage()); float[] matrix = new float[6]; affineTransform.GetMatrix(matrix); canvas.AddImageWithTransformationMatrix(image, matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); pdfDoc.Close(); }
protected internal virtual float[] ApplyRotation() { float dx = 0; float dy = 0; if (!IsPositioned()) { Point shift = GetLayoutShiftAndRotatedPoints(new List <Point>(), 0, 0); dy = (float)shift.GetY(); dx = (float)shift.GetX(); } float? angle = this.GetPropertyAsFloat(Property.ROTATION_ANGLE); AffineTransform transform = new AffineTransform(); transform.Rotate((float)angle); float[] ctm = new float[6]; transform.GetMatrix(ctm); ctm[4] = (float)this.GetPropertyAsFloat(Property.ROTATION_POINT_X) + dx; ctm[5] = (float)this.GetPropertyAsFloat(Property.ROTATION_POINT_Y) + dy; return(ctm); }
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> /// Transforms the source <CODE>BufferedImage</CODE> and stores the results /// in the destination <CODE>BufferedImage</CODE>. /// If the color models for the two images do not match, a color /// conversion into the destination color model is performed. /// If the destination image is null, /// a <CODE>BufferedImage</CODE> is created with the source /// <CODE>ColorModel</CODE>. /// <para> /// The coordinates of the rectangle returned by /// <code>getBounds2D(BufferedImage)</code> /// are not necessarily the same as the coordinates of the /// <code>BufferedImage</code> returned by this method. If the /// upper-left corner coordinates of the rectangle are /// negative then this part of the rectangle is not drawn. If the /// upper-left corner coordinates of the rectangle are positive /// then the filtered image is drawn at that position in the /// destination <code>BufferedImage</code>. /// </para> /// <para> /// An <CODE>IllegalArgumentException</CODE> is thrown if the source is /// the same as the destination. /// /// </para> /// </summary> /// <param name="src"> The <CODE>BufferedImage</CODE> to transform. </param> /// <param name="dst"> The <CODE>BufferedImage</CODE> in which to store the results /// of the transformation. /// </param> /// <returns> The filtered <CODE>BufferedImage</CODE>. </returns> /// <exception cref="IllegalArgumentException"> if <code>src</code> and /// <code>dst</code> are the same </exception> /// <exception cref="ImagingOpException"> if the image cannot be transformed /// because of a data-processing error that might be /// caused by an invalid image format, tile format, or /// image-processing operation, or any other unsupported /// operation. </exception> public BufferedImage Filter(BufferedImage src, BufferedImage dst) { if (src == null) { throw new NullPointerException("src image is null"); } if (src == dst) { throw new IllegalArgumentException("src image cannot be the " + "same as the dst image"); } bool needToConvert = false; ColorModel srcCM = src.ColorModel; ColorModel dstCM; BufferedImage origDst = dst; if (dst == null) { dst = CreateCompatibleDestImage(src, null); dstCM = srcCM; origDst = dst; } else { dstCM = dst.ColorModel; if (srcCM.ColorSpace.Type != dstCM.ColorSpace.Type) { int type = Xform.Type; bool needTrans = ((type & (Xform.TYPE_MASK_ROTATION | Xform.TYPE_GENERAL_TRANSFORM)) != 0); if (!needTrans && type != Xform.TYPE_TRANSLATION && type != Xform.TYPE_IDENTITY) { double[] mtx = new double[4]; Xform.GetMatrix(mtx); // Check out the matrix. A non-integral scale will force ARGB // since the edge conditions can't be guaranteed. needTrans = (mtx[0] != (int)mtx[0] || mtx[3] != (int)mtx[3]); } if (needTrans && srcCM.Transparency == java.awt.Transparency_Fields.OPAQUE) { // Need to convert first ColorConvertOp ccop = new ColorConvertOp(Hints); BufferedImage tmpSrc = null; int sw = src.Width; int sh = src.Height; if (dstCM.Transparency == java.awt.Transparency_Fields.OPAQUE) { tmpSrc = new BufferedImage(sw, sh, BufferedImage.TYPE_INT_ARGB); } else { WritableRaster r = dstCM.CreateCompatibleWritableRaster(sw, sh); tmpSrc = new BufferedImage(dstCM, r, dstCM.AlphaPremultiplied, null); } src = ccop.Filter(src, tmpSrc); } else { needToConvert = true; dst = CreateCompatibleDestImage(src, null); } } } if (InterpolationType_Renamed != TYPE_NEAREST_NEIGHBOR && dst.ColorModel is IndexColorModel) { dst = new BufferedImage(dst.Width, dst.Height, BufferedImage.TYPE_INT_ARGB); } if (ImagingLib.filter(this, src, dst) == null) { throw new ImagingOpException("Unable to transform src image"); } if (needToConvert) { ColorConvertOp ccop = new ColorConvertOp(Hints); ccop.Filter(dst, origDst); } else if (origDst != dst) { java.awt.Graphics2D g = origDst.CreateGraphics(); try { g.Composite = AlphaComposite.Src; g.DrawImage(dst, 0, 0, null); } finally { g.Dispose(); } } return(origDst); }
/// <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(); }
/// <summary> /// Constructor for MultipleGradientPaintContext superclass. /// </summary> protected internal MultipleGradientPaintContext(MultipleGradientPaint mgp, ColorModel cm, Rectangle deviceBounds, Rectangle2D userBounds, AffineTransform t, RenderingHints hints, float[] fractions, Color[] colors, CycleMethod cycleMethod, ColorSpaceType colorSpace) { if (deviceBounds == null) { throw new NullPointerException("Device bounds cannot be null"); } if (userBounds == null) { throw new NullPointerException("User bounds cannot be null"); } if (t == null) { throw new NullPointerException("Transform cannot be null"); } if (hints == null) { throw new NullPointerException("RenderingHints cannot be null"); } // The inverse transform is needed to go from device to user space. // Get all the components of the inverse transform matrix. AffineTransform tInv; try { // the following assumes that the caller has copied the incoming // transform and is not concerned about it being modified t.Invert(); tInv = t; } catch (NoninvertibleTransformException) { // just use identity transform in this case; better to show // (incorrect) results than to throw an exception and/or no-op tInv = new AffineTransform(); } double[] m = new double[6]; tInv.GetMatrix(m); A00 = (float)m[0]; A10 = (float)m[1]; A01 = (float)m[2]; A11 = (float)m[3]; A02 = (float)m[4]; A12 = (float)m[5]; // copy some flags this.CycleMethod = cycleMethod; this.ColorSpace = colorSpace; // we can avoid copying this array since we do not modify its values this.Fractions = fractions; // note that only one of these values can ever be non-null (we either // store the fast gradient array or the slow one, but never both // at the same time) int[] gradient = (mgp.Gradient != null) ? mgp.Gradient.get() : null; int[][] gradients = (mgp.Gradients != null) ? mgp.Gradients.get() : null; if (gradient == null && gradients == null) { // we need to (re)create the appropriate values CalculateLookupData(colors); // now cache the calculated values in the // MultipleGradientPaint instance for future use mgp.Model = this.Model; mgp.NormalizedIntervals = this.NormalizedIntervals; mgp.IsSimpleLookup = this.IsSimpleLookup; if (IsSimpleLookup) { // only cache the fast array mgp.FastGradientArraySize = this.FastGradientArraySize; mgp.Gradient = new SoftReference <int[]>(this.Gradient); } else { // only cache the slow array mgp.Gradients = new SoftReference <int[][]>(this.Gradients); } } else { // use the values cached in the MultipleGradientPaint instance this.Model = mgp.Model; this.NormalizedIntervals = mgp.NormalizedIntervals; this.IsSimpleLookup = mgp.IsSimpleLookup; this.Gradient = gradient; this.FastGradientArraySize = mgp.FastGradientArraySize; this.Gradients = gradients; } }