// =========================================================================== public override void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 PdfContentByte canvas = writer.DirectContent; PdfShading axial = PdfShading.SimpleAxial(writer, 36, 716, 396, 788, BaseColor.ORANGE, BaseColor.BLUE ); canvas.PaintShading(axial); document.NewPage(); PdfShading radial = PdfShading.SimpleRadial(writer, 200, 700, 50, 300, 700, 100, new BaseColor(0xFF, 0xF7, 0x94), new BaseColor(0xF7, 0x8A, 0x6B), false, false ); canvas.PaintShading(radial); PdfShadingPattern shading = new PdfShadingPattern(axial); ColorRectangle(canvas, new ShadingColor(shading), 150, 420, 126, 126); canvas.SetShadingFill(shading); canvas.Rectangle(300, 420, 126, 126); canvas.FillStroke(); } }
/// <summary> /// Builds a shading pattern from an radial gradient brush. /// </summary> public static PdfShadingPattern BuildFromRadialGradientBrush(DocumentRenderingContext context, RadialGradientBrush brush, XRect boundingBox, XMatrix transform) { RadialShadingBuilder builder = new RadialShadingBuilder(context); PdfShadingPattern pattern = builder.BuildPattern(brush, boundingBox, transform); return(pattern); }
/// <summary> /// Builds a pattern from a linear gradient brush. /// </summary> public static PdfShadingPattern BuildPatternFromLinearGradientBrush(DocumentRenderingContext context, LinearGradientBrush brush, XMatrix transform) { LinearShadingBuilder builder = new LinearShadingBuilder(context); PdfShadingPattern pattern = builder.BuildShadingPattern(brush, transform); return(pattern); }
public void RealizeBrush(XBrush brush, PdfColorMode colorMode, int renderingMode, double fontEmSize, bool isForPen = false) { // Rendering mode 2 is used for bold simulation. // Reference: TABLE 5.3 Text rendering modes / Page 402 XSolidBrush solidBrush = brush as XSolidBrush; if (solidBrush != null) { XColor color = solidBrush.Color; bool overPrint = solidBrush.Overprint; if (renderingMode == 0) { RealizeFillColor(color, overPrint, colorMode); } else if (renderingMode == 2) { // Come here in case of bold simulation. RealizeFillColor(color, false, colorMode); //color = XColors.Green; RealizePen(new XPen(color, fontEmSize * Const.BoldEmphasis), colorMode); } else { throw new InvalidOperationException("Only rendering modes 0 and 2 are currently supported."); } } else { if (renderingMode != 0) { throw new InvalidOperationException("Rendering modes other than 0 can only be used with solid color brushes."); } if (brush is XBaseGradientBrush gradientBrush) { Debug.Assert(UnrealizedCtm.IsIdentity, "Must realize ctm first."); XMatrix matrix = _renderer.DefaultViewMatrix; matrix.Prepend(EffectiveCtm); PdfShadingPattern pattern = new PdfShadingPattern(_renderer.Owner); pattern.SetupFromBrush(gradientBrush, matrix, _renderer); string name = _renderer.Resources.AddPattern(pattern); if (isForPen) { _renderer.AppendFormatString("/Pattern CS\n", name); _renderer.AppendFormatString("{0} SCN\n", name); } else { _renderer.AppendFormatString("/Pattern cs\n", name); _renderer.AppendFormatString("{0} scn\n", name); } // Invalidate fill color. _realizedFillColor = XColor.Empty; } } }
public void RealizeBrush(XBrush brush, PdfColorMode colorMode) { if (brush is XSolidBrush) { XColor color = ((XSolidBrush)brush).Color; color = ColorSpaceHelper.EnsureColorMode(colorMode, color); if (colorMode != PdfColorMode.Cmyk) { if (this.realizedFillColor.Rgb != color.Rgb) { this.renderer.Append(PdfEncoders.ToString(color, PdfColorMode.Rgb)); this.renderer.Append(" rg\n"); } } else { if (!ColorSpaceHelper.IsEqualCmyk(this.realizedFillColor, color)) { this.renderer.Append(PdfEncoders.ToString(color, PdfColorMode.Cmyk)); this.renderer.Append(" k\n"); } } if (this.renderer.Owner.Version >= 14 && this.realizedFillColor.A != color.A) { PdfExtGState extGState = this.renderer.Owner.ExtGStateTable.GetExtGStateNonStroke(color.A); string gs = this.renderer.Resources.AddExtGState(extGState); this.renderer.AppendFormat("{0} gs\n", gs); // Must create transparany group if (this.renderer.page != null && color.A < 1) { this.renderer.page.transparencyUsed = true; } } this.realizedFillColor = color; } else if (brush is XLinearGradientBrush) { XMatrix matrix = this.renderer.defaultViewMatrix; matrix.Prepend(this.Transform); PdfShadingPattern pattern = new PdfShadingPattern(this.renderer.Owner); pattern.SetupFromBrush((XLinearGradientBrush)brush, matrix); string name = this.renderer.Resources.AddPattern(pattern); this.renderer.AppendFormat("/Pattern cs\n", name); this.renderer.AppendFormat("{0} scn\n", name); // Invalidate fill color this.realizedFillColor = XColor.Empty; } }
private void Form1_Load(object sender, EventArgs e) { //Test file name string TestFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf"); //Standard iTextSharp setup using (FileStream fs = new FileStream(TestFile, FileMode.Create, FileAccess.Write, FileShare.None)) { using (Document doc = new Document(PageSize.LETTER)) { using (PdfWriter w = PdfWriter.GetInstance(doc, fs)) { //Open the document for writing doc.Open(); //Create a shading object. The (x,y)'s appear to be document-level instead of cell-level so they need to be played with PdfShading shading = PdfShading.SimpleAxial(w, 0, 700, 300, 700, BaseColor.BLUE, BaseColor.RED); //Create a pattern from our shading object PdfShadingPattern pattern = new PdfShadingPattern(shading); //Create a color from our patter ShadingColor color = new ShadingColor(pattern); //Create a standard two column table PdfPTable t = new PdfPTable(2); //Add a text cell setting the background color through object initialization t.AddCell(new PdfPCell(new Phrase("Hello")) { BackgroundColor = color }); //Add another cell with everything inline. Notice that the (x,y)'s have been updated t.AddCell(new PdfPCell(new Phrase("World")) { BackgroundColor = new ShadingColor(new PdfShadingPattern(PdfShading.SimpleAxial(w, 400, 700, 600, 700, BaseColor.PINK, BaseColor.CYAN))) }); //Add the table to the document doc.Add(t); //Close the document doc.Close(); } } } this.Close(); }
private void setPaint(Paint paint, boolean invert, double xoffset, double yoffset) { this.paint = paint; if (paint is Color) { cb.setColorFill((Color)paint); } else if (paint is GradientPaint) { GradientPaint gp = (GradientPaint)paint; Point2D p1 = gp.getPoint1(); transform.transform(p1, p1); Point2D p2 = gp.getPoint2(); transform.transform(p2, p2); Color c1 = gp.getColor1(); Color c2 = gp.getColor2(); PdfShading shading = PdfShading.simpleAxial(cb.getPdfWriter(), (float)p1.getX(), (float)p1.getY(), (float)p2.getX(), (float)p2.getY(), c1, c2); PdfShadingPattern pat = new PdfShadingPattern(shading); cb.setShadingFill(pat); } else { try { BufferedImage img = null; int type = BufferedImage.TYPE_4BYTE_ABGR; if (paint.getTransparency() == Transparency.OPAQUE) { type = BufferedImage.TYPE_3BYTE_BGR; } img = new BufferedImage((int)width, (int)height, type); Graphics2D g = (Graphics2D)img.getGraphics(); Shape fillRect = new Rectangle2D.Double(0, 0, img.getWidth(), img.getHeight()); g.setPaint(paint); g.fill(fillRect); if (invert) { AffineTransform tx = new AffineTransform(); tx.scale(1, -1); tx.translate(-xoffset, -yoffset); g.drawImage(img, tx, null); } com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(img, null); PdfPatternPainter pattern = cb.createPattern(width, height); image.setAbsolutePosition(0, 0); pattern.addImage(image); cb.setPatternFill(pattern); } catch (Exception ex) { cb.setColorFill(Color.gray); } } }
public void TableLayout(PdfPTable table, float[][] widths, float[] heights, int headerRows, int rowStart, PdfContentByte[] canvases) { BaseColor gradientStart = ...; BaseColor gradientEnd = ...); float[] topWidths = widths[0]; PdfContentByte cb = canvases[PdfPTable.BACKGROUNDCANVAS]; Rectangle rectangle = new Rectangle(topWidths[0], heights[heights.Length - 1], topWidths[topWidths.Length - 1], heights[0]); PdfShading shading = PdfShading.SimpleAxial(writer, rectangle.Left, rectangle.Top, rectangle.Left, rectangle.Bottom, gradientStart, gradientEnd); PdfShadingPattern pattern = new PdfShadingPattern(shading); cb.SetShadingFill(pattern); cb.Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, rectangle.Height); cb.Fill(); }
// --------------------------------------------------------------------------- /** * Prints a square and fills half of it with a gray rectangle. * * @param x * @param y * @param cb * @throws Exception */ public static void PictureBackdrop(float x, float y, PdfContentByte cb, PdfWriter writer) { PdfShading axial = PdfShading.SimpleAxial(writer, x, y, x + 200, y, BaseColor.YELLOW, BaseColor.RED ); PdfShadingPattern axialPattern = new PdfShadingPattern(axial); cb.SetShadingFill(axialPattern); cb.SetColorStroke(BaseColor.BLACK); cb.SetLineWidth(2); cb.Rectangle(x, y, 200, 200); cb.FillStroke(); }
public void Verify_ShadingPatternColor_CanBeCreated() { var pdfFilePath = TestUtils.GetOutputFileName(); var stream = new FileStream(pdfFilePath, FileMode.Create); // step 1 var document = new Document(); // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); // step 3 document.AddAuthor(TestUtils.Author); document.Open(); // step 4 PdfContentByte canvas = writer.DirectContent; PdfShading axial = PdfShading.SimpleAxial(writer, 36, 716, 396, 788, BaseColor.Orange, BaseColor.Blue ); canvas.PaintShading(axial); document.NewPage(); PdfShading radial = PdfShading.SimpleRadial(writer, 200, 700, 50, 300, 700, 100, new BaseColor(0xFF, 0xF7, 0x94), new BaseColor(0xF7, 0x8A, 0x6B), false, false ); canvas.PaintShading(radial); PdfShadingPattern shading = new PdfShadingPattern(axial); colorRectangle(canvas, new ShadingColor(shading), 150, 420, 126, 126); canvas.SetShadingFill(shading); canvas.Rectangle(300, 420, 126, 126); canvas.FillStroke(); document.Close(); stream.Dispose(); TestUtils.VerifyPdfFileIsReadable(pdfFilePath); }
public void CellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) { //Create a shading object with cell-specific coords PdfShading shading = PdfShading.SimpleAxial(w, position.Left, position.Bottom, position.Right, position.Top, BaseColor.BLUE, BaseColor.RED); //Create a pattern from our shading object PdfShadingPattern pattern = new PdfShadingPattern(shading); //Create a color from our patter ShadingColor color = new ShadingColor(pattern); //Get the background canvas. NOTE, If using an older version of iTextSharp (4.x) you might need to get the canvas in a different way PdfContentByte cb = canvases[PdfPTable.BACKGROUNDCANVAS]; //Set the background color of the given rectable to our shading pattern position.BackgroundColor = color; //Fill the rectangle cb.Rectangle(position); }
/// <summary> /// Builds a PdfShadingPattern from the specified brush. /// </summary> PdfShadingPattern BuildShadingPattern(LinearGradientBrush brush, XMatrix transform) { //<< // /Matrix [0.75 0 0 -0.75 8 470.4] // /PatternType 2 // /Shading 22 0 R // /Type /Pattern //>> XMatrix matrix = transform; PdfShadingPattern pattern = Context.PdfDocument.Internals.CreateIndirectObject <PdfShadingPattern>(); pattern.Elements.SetInteger(PdfShadingPattern.Keys.PatternType, 2); // Shading pattern.Elements.SetMatrix(PdfShadingPattern.Keys.Matrix, matrix); PdfShading shading = BuildShading(brush); Context.PdfDocument.Internals.AddObject(shading); pattern.Elements.SetReference(PdfShadingPattern.Keys.Shading, shading); return(pattern); }
/// <summary> /// Draws a rectangular gradient background color. /// </summary> /// <param name="position">The coordinates of the cell</param> /// <param name="canvases">An array of PdfContentByte to add text or graphics</param> /// <param name="startColor">Gradient's Start Color</param> /// <param name="endColor">Gradient's End Color</param> public static void DrawGradientBackground(this Rectangle position, PdfContentByte[] canvases, BaseColor startColor, BaseColor endColor) { if (startColor == null || endColor == null) { return; } var cb = canvases[PdfPTable.BACKGROUNDCANVAS]; cb.SaveState(); var shading = PdfShading.SimpleAxial( cb.PdfWriter, position.Left, position.Top, position.Left, position.Bottom, startColor, endColor); var shadingPattern = new PdfShadingPattern(shading); cb.SetShadingFill(shadingPattern); cb.Rectangle(position.Left, position.Bottom, position.Width, position.Height); cb.Fill(); cb.RestoreState(); }
private static void DrawPatterns(PdfPage page, PdfFont titleFont, PdfFont sectionFont) { PdfBrush brush = new PdfBrush(); PdfPen blackPen = new PdfPen(PdfRgbColor.Black, 1); PdfPen darkRedPen = new PdfPen(new PdfRgbColor(0xFF, 0x40, 0x40), 0.8); PdfPen darkOrangePen = new PdfPen(new PdfRgbColor(0xA6, 0x4B, 0x00), 0.8); PdfPen darkCyanPen = new PdfPen(new PdfRgbColor(0x00, 0x63, 0x63), 0.8); PdfPen darkGreenPen = new PdfPen(new PdfRgbColor(0x00, 0x85, 0x00), 0.8); PdfBrush lightRedBrush = new PdfBrush(new PdfRgbColor(0xFF, 0x73, 0x73)); PdfBrush lightOrangeBrush = new PdfBrush(new PdfRgbColor(0xFF, 0x96, 0x40)); PdfBrush lightCyanBrush = new PdfBrush(new PdfRgbColor(0x33, 0xCC, 0xCC)); PdfBrush lightGreenBrush = new PdfBrush(new PdfRgbColor(0x67, 0xE6, 0x67)); page.Graphics.DrawString("Patterns", titleFont, brush, 20, 50); page.Graphics.DrawString("Colored patterns", sectionFont, brush, 25, 70); // Create the pattern visual appearance. PdfColoredTilingPattern ctp = new PdfColoredTilingPattern(20, 20); // Red circle ctp.Graphics.DrawEllipse(darkRedPen, lightRedBrush, 1, 1, 8, 8); // Cyan square ctp.Graphics.DrawRectangle(darkCyanPen, lightCyanBrush, 11, 1, 8, 8); // Green diamond PdfPath diamondPath = new PdfPath(); diamondPath.StartSubpath(1, 15); diamondPath.AddPolyLineTo(new PdfPoint[] { new PdfPoint(5, 11), new PdfPoint(9, 15), new PdfPoint(5, 19) }); diamondPath.CloseSubpath(); ctp.Graphics.DrawPath(darkGreenPen, lightGreenBrush, diamondPath); // Orange triangle PdfPath trianglePath = new PdfPath(); trianglePath.StartSubpath(11, 19); trianglePath.AddPolyLineTo(new PdfPoint[] { new PdfPoint(15, 11), new PdfPoint(19, 19) }); trianglePath.CloseSubpath(); ctp.Graphics.DrawPath(darkOrangePen, lightOrangeBrush, trianglePath); // Create a pattern colorspace from the pattern object. PdfPatternColorSpace coloredPatternColorSpace = new PdfPatternColorSpace(ctp); // Create a color based on the pattern colorspace. PdfPatternColor coloredPatternColor = new PdfPatternColor(coloredPatternColorSpace); // The pen and brush use the pattern color like any other color. PdfPatternBrush patternBrush = new PdfPatternBrush(coloredPatternColor); PdfPatternPen patternPen = new PdfPatternPen(coloredPatternColor, 40); page.Graphics.DrawEllipse(patternBrush, 25, 90, 250, 200); page.Graphics.DrawRoundRectangle(patternPen, 310, 110, 250, 160, 100, 100); page.Graphics.DrawString("Uncolored patterns", sectionFont, brush, 25, 300); // Create the pattern visual appearance. PdfUncoloredTilingPattern uctp = new PdfUncoloredTilingPattern(20, 20); // A pen without color is used to create the pattern content. PdfPen noColorPen = new PdfPen(null, 0.8); // Circle uctp.Graphics.DrawEllipse(noColorPen, 1, 1, 8, 8); // Square uctp.Graphics.DrawRectangle(noColorPen, 11, 1, 8, 8); // Diamond diamondPath = new PdfPath(); diamondPath.StartSubpath(1, 15); diamondPath.AddPolyLineTo(new PdfPoint[] { new PdfPoint(5, 11), new PdfPoint(9, 15), new PdfPoint(5, 19) }); diamondPath.CloseSubpath(); uctp.Graphics.DrawPath(noColorPen, diamondPath); // Triangle trianglePath = new PdfPath(); trianglePath.StartSubpath(11, 19); trianglePath.AddPolyLineTo(new PdfPoint[] { new PdfPoint(15, 11), new PdfPoint(19, 19) }); trianglePath.CloseSubpath(); uctp.Graphics.DrawPath(noColorPen, trianglePath); // Create a pattern colorspace from the pattern object. PdfPatternColorSpace uncoloredPatternColorSpace = new PdfPatternColorSpace(uctp); // Create a color based on the pattern colorspace. PdfPatternColor uncoloredPatternColor = new PdfPatternColor(uncoloredPatternColorSpace); // The pen and brush use the pattern color like any other color. patternBrush = new PdfPatternBrush(uncoloredPatternColor); // Before using the uncolored pattern set the color that will be used to paint the pattern. patternBrush.UncoloredPatternPaintColor = new PdfRgbColor(0xFF, 0x40, 0x40); page.Graphics.DrawEllipse(patternBrush, 25, 320, 125, 200); patternBrush.UncoloredPatternPaintColor = new PdfRgbColor(0xA6, 0x4B, 0x00); page.Graphics.DrawEllipse(patternBrush, 175, 320, 125, 200); patternBrush.UncoloredPatternPaintColor = new PdfRgbColor(0x00, 0x63, 0x63); page.Graphics.DrawEllipse(patternBrush, 325, 320, 125, 200); patternBrush.UncoloredPatternPaintColor = new PdfRgbColor(0x00, 0x85, 0x00); page.Graphics.DrawEllipse(patternBrush, 475, 320, 125, 200); page.Graphics.DrawString("Shading patterns", sectionFont, brush, 25, 550); // Create the pattern visual appearance. PdfAxialShading horizontalShading = new PdfAxialShading(); horizontalShading.StartColor = new PdfRgbColor(255, 0, 0); horizontalShading.EndColor = new PdfRgbColor(0, 0, 255); horizontalShading.StartPoint = new PdfPoint(25, 600); horizontalShading.EndPoint = new PdfPoint(575, 600); PdfShadingPattern sp = new PdfShadingPattern(horizontalShading); // Create a pattern colorspace from the pattern object. PdfPatternColorSpace shadingPatternColorSpace = new PdfPatternColorSpace(sp); // Create a color based on the pattern colorspace. PdfPatternColor shadingPatternColor = new PdfPatternColor(shadingPatternColorSpace); // The pen and brush use the pattern color like any other color. patternPen = new PdfPatternPen(shadingPatternColor, 40); page.Graphics.DrawEllipse(patternPen, 50, 600, 500, 150); page.Graphics.CompressAndClose(); }
PdfShadingPattern BuildPattern(RadialGradientBrush brush, XRect boundingBox, XMatrix transform) { //<< // /BBox [0 0 600 760] // /Length 123 // /Matrix [0.75 0 0 -0.75 0 480] // /PaintType 1 // /PatternType 1 // /Resources // << // /ColorSpace // << // /CS0 12 0 R // /CS1 12 0 R // >> // /ExtGState // << // /GS0 10 0 R // /GS1 16 0 R // >> // /Shading // << // /Sh0 15 0 R // >> // >> // /TilingType 3 // /Type /Pattern // /XStep 600 // /YStep 1520 //>> //stream // /CS0 cs 1 0 0 scn // 1 i // /GS0 gs // 0 0 600 759.999 re // f // q // 0 0 600 760 re // W n // q // 0 g // /GS1 gs // 1 0 0 0.5 0 0 cm // BX /Sh0 sh EX Q // Q //endstream XRect bbox = new XRect(-600, -700, 1200, 1520); // HACK XMatrix matrix = transform; //matrix.Prepend(brush.Transform.Matrix); double xStep = 600; double yStep = 1520; // HACK PdfShadingPattern pattern = Context.PdfDocument.Internals.CreateIndirectObject <PdfShadingPattern>(); pattern.Elements.SetInteger(PdfTilingPattern.Keys.PatternType, 1); // Tiling pattern.Elements.SetInteger(PdfTilingPattern.Keys.PaintType, 1); // Color pattern.Elements.SetInteger(PdfTilingPattern.Keys.TilingType, 3); // Constant spacing and faster tiling pattern.Elements.SetMatrix(PdfTilingPattern.Keys.Matrix, matrix); pattern.Elements.SetRectangle(PdfTilingPattern.Keys.BBox, new PdfRectangle(bbox)); pattern.Elements.SetReal(PdfTilingPattern.Keys.XStep, xStep); pattern.Elements.SetReal(PdfTilingPattern.Keys.YStep, yStep); double dx = 2 * brush.RadiusX; double dy = 2 * brush.RadiusY; XRect brushBox = new XRect(brush.Center.X - brush.RadiusX, brush.Center.Y - brush.RadiusY, dx, dy); Debug.Assert(dx * dy > 0, "Radius is 0."); double scaleX, scaleY; if (dx > dy) { scaleX = 1; scaleY = dy / dx; } else { scaleX = dx / dy; scaleY = 1; } PdfColorMode colorMode = PdfColorMode.Rgb; PdfDictionary funcReflected; PdfDictionary funcRegular = BuildShadingFunction(brush.GradientStops, false, colorMode, true, out funcReflected); if (brush.SpreadMethod != SpreadMethod.Pad) { if (CanOptimizeForTwoColors(brush.GradientStops)) { PdfDictionary dummy; funcReflected = BuildShadingFunction(brush.GradientStops, false, colorMode, false, out dummy); } else { Context.PdfDocument.Internals.AddObject(funcRegular); } } //PdfShading shading = BuildShading(brush, scaleX, scaleY); int shadingCount = 1; if (brush.SpreadMethod != SpreadMethod.Pad) { // TODO: Calculate number of required shadings shadingCount = Convert.ToInt32(Math.Max(boundingBox.Width / (2 * brush.RadiusX), boundingBox.Height / (2 * brush.RadiusY)) + 1); // HACK: Rule of thumb, better than nothing shadingCount *= 2; } PdfShading[] shadings = new PdfShading[shadingCount]; // Create the shadings for (int idx = 0; idx < shadingCount; idx++) { PdfShading shading = BuildShading2(brush, scaleX, scaleY, idx, brush.SpreadMethod == SpreadMethod.Reflect && idx % 2 == 1 ? funcReflected : funcRegular); shadings[idx] = shading; } PdfContentWriter writer = new PdfContentWriter(Context, pattern); writer.BeginContentRaw(); // Fill background (even if spread method is not pad) writer.WriteLiteral("q /DeviceRGB cs\n"); //writer.WriteLiteral(PdfEncoders.ToString(clr0, colorMode) + " rg 1 i\n"); writer.WriteLiteral(PdfEncoders.ToString(brush.GradientStops[brush.GradientStops.Count - 1].Color, PdfColorMode.Rgb) + " rg 1 i\n"); writer.WriteLiteral("1 i\n"); PdfExtGState gs = Context.PdfDocument.Internals.CreateIndirectObject <PdfExtGState>(); gs.SetDefault1(); writer.WriteGraphicsState(gs); writer.WriteLiteral("0 0 600 760 re f\n"); XMatrix mat = brush.Transform.Matrix; if (!mat.IsIdentity) { writer.WriteMatrix(mat); } // Just work: silly loop thru shadings for (int idx = shadingCount - 1; idx >= 0; idx--) { writer.WriteLiteral("q 0 0 600 760 re W n\n"); writer.WriteLiteral("q 0 g\n"); gs = Context.PdfDocument.Internals.CreateIndirectObject <PdfExtGState>(); gs.SetDefault2(); writer.WriteGraphicsState(gs); XMatrix transformation = new XMatrix(scaleX, 0, 0, scaleY, 0, 0); writer.WriteMatrix(transformation); string shName = writer.Resources.AddShading(shadings[idx]); writer.WriteLiteral("BX " + shName + " sh EX Q Q\n"); } writer.WriteLiteral("Q\n"); writer.EndContent(); return(pattern); }
/// <summary> /// Writes a Path to the content stream. /// </summary> private void WritePath(Path path) { if (WriteSingleLineStrokeWithSpecialCaps(path)) { return; } WriteSaveState("begin Path", path.Name); // Transform also affects clipping and opacity mask if (path.RenderTransform != null && this.renderMode == RenderMode.Default) { MultiplyTransform(path.RenderTransform); WriteRenderTransform(path.RenderTransform); } if (path.Clip != null && this.renderMode == RenderMode.Default) { WriteClip(path.Clip); } if (path.Opacity < 1) { MultiplyOpacity(path.Opacity); } if (path.OpacityMask != null) { WriteOpacityMask(path.OpacityMask); } if (path.Fill == null) { if (path.Stroke != null) { WriteStrokeGeometry(path); } else { Debug.Assert(false, "??? Path with neither Stroke nor Fill encountered."); } } else { SolidColorBrush sBrush; LinearGradientBrush lgBrush; RadialGradientBrush rgBrush; ImageBrush iBrush; VisualBrush vBrush; if ((sBrush = path.Fill as SolidColorBrush) != null) { Color color = sBrush.Color; double opacity = Opacity * color.ScA; if (opacity < 1) { RealizeFillOpacity(opacity); } WriteRgb(color, " rg\n"); if (path.Stroke != null) { RealizeStroke(path); } WriteGeometry(path.Data); WritePathFillStroke(path); } else if ((lgBrush = path.Fill as LinearGradientBrush) != null) { // TODO: For better visual compatibility use a Shading Pattern if Opacity is not 1 and // the Stroke Style is not solid. Acrobat 8 ignores this case. PdfExtGState xgState = Context.PdfDocument.Internals.CreateIndirectObject <PdfExtGState>(); xgState.SetDefault1(); double opacity = Opacity * lgBrush.Opacity;; if (opacity < 1) { xgState.StrokeAlpha = opacity; xgState.NonStrokeAlpha = opacity; } RealizeExtGState(xgState); // 1st draw fill if (lgBrush.GradientStops.HasTransparency) { // Create a FormXObject with a soft mask PdfFormXObject form = LinearShadingBuilder.BuildFormFromLinearGradientBrush(Context, lgBrush, path.Data); string foName = Resources.AddForm(form); WriteLiteral(foName + " Do\n"); } else { // Create just a shading PdfShading shading = LinearShadingBuilder.BuildShadingFromLinearGradientBrush(Context, lgBrush); string shName = Resources.AddShading(shading); WriteLiteral("q\n"); WriteClip(path.Data); WriteLiteral("BX " + shName + " sh EX Q\n"); } // 2nd draw stroke if (path.Stroke != null) { WriteStrokeGeometry(path); } } else if ((rgBrush = path.Fill as RadialGradientBrush) != null) { PdfExtGState xgState = Context.PdfDocument.Internals.CreateIndirectObject <PdfExtGState>(); xgState.SetDefault1(); double avGradientOpacity = rgBrush.GradientStops.GetAverageAlpha(); // HACK double opacity = Opacity * rgBrush.Opacity * avGradientOpacity; if (opacity < 1) { xgState.StrokeAlpha = opacity; xgState.NonStrokeAlpha = opacity; } //RealizeExtGState(xgState); XRect boundingBox = path.Data.GetBoundingBox(); // Always creates a pattern, because the background must be filled PdfShadingPattern pattern = RadialShadingBuilder.BuildFromRadialGradientBrush(Context, rgBrush, boundingBox, Transform); string paName = Resources.AddPattern(pattern); // stream // /CS0 cs /P0 scn // /GS0 gs // 0 480 180 -90 re // f* // endstream // endobj WriteLiteral("/Pattern cs " + paName + " scn\n"); // move to here: RealizeExtGState(xgState); RealizeExtGState(xgState); WriteGeometry(path.Data); if (path.Data.FillRule == FillRule.NonZero) // NonZero means Winding { WriteLiteral("f\n"); } else { WriteLiteral("f*\n"); } // 2nd draw stroke if (path.Stroke != null) { WriteStrokeGeometry(path); } } else if ((iBrush = path.Fill as ImageBrush) != null) { PdfExtGState xgState = Context.PdfDocument.Internals.CreateIndirectObject <PdfExtGState>(); xgState.SetDefault1(); double opacity = Opacity * iBrush.Opacity; if (opacity <= 1) { xgState.StrokeAlpha = opacity; xgState.NonStrokeAlpha = opacity; } RealizeExtGState(xgState); // 1st draw fill PdfTilingPattern pattern = TilingPatternBuilder.BuildFromImageBrush(Context, iBrush, Transform); string name = Resources.AddPattern(pattern); WriteLiteral("/Pattern cs " + name + " scn\n"); WriteGeometry(path.Data); WritePathFillStroke(path); // 2nd draw stroke if (path.Stroke != null) { WriteStrokeGeometry(path); } } else if ((vBrush = path.Fill as VisualBrush) != null) { PdfExtGState xgState = Context.PdfDocument.Internals.CreateIndirectObject <PdfExtGState>(); xgState.SetDefault1(); double opacity = Opacity * vBrush.Opacity; if (opacity < 1) { xgState.StrokeAlpha = opacity; xgState.NonStrokeAlpha = opacity; } RealizeExtGState(xgState); // 1st draw fill PdfTilingPattern pattern = TilingPatternBuilder.BuildFromVisualBrush(Context, vBrush, Transform); string name = Resources.AddPattern(pattern); WriteLiteral("/Pattern cs " + name + " scn\n"); WriteGeometry(path.Data); WritePathFillStroke(path); // 2nd draw stroke if (path.Stroke != null) { WriteStrokeGeometry(path); } } else { Debug.Assert(false, "Unknown brush type encountered."); } } WriteRestoreState("end Path", path.Name); }
/// <summary> /// Strokes the path geometry with the Stroke brush. /// </summary> private void WriteStrokeGeometry(Path path) { if (path.Stroke == null) { return; } SolidColorBrush sBrush; LinearGradientBrush lgBrush; RadialGradientBrush rgBrush; VisualBrush vBrush; ImageBrush iBrush; //if (path.Stroke != null && this.renderMode == RenderMode.Default) // HACK if ((sBrush = path.Stroke as SolidColorBrush) != null) { RealizeStroke(path); WriteGeometry(path.Data); WriteLiteral("S\n"); } else if ((lgBrush = path.Stroke as LinearGradientBrush) != null) { PdfExtGState xgState = Context.PdfDocument.Internals.CreateIndirectObject <PdfExtGState>(); xgState.SetDefault1(); double opacity = Opacity * lgBrush.Opacity;; if (opacity < 1) { xgState.StrokeAlpha = opacity; xgState.NonStrokeAlpha = opacity; } RealizeExtGState(xgState); // /CS1 CS /P0 SCN // 7.5 w // q 1 0 0 1 15.5 462.9 cm // 0 0 m // 153 0 l // 153 -93 l // 0 -93 l // h // S // Q if (lgBrush.GradientStops.HasTransparency) { // TODO: Create Form PdfShadingPattern pattern = LinearShadingBuilder.BuildPatternFromLinearGradientBrush(Context, lgBrush, Transform); string paName = Resources.AddPattern(pattern); WriteLiteral("/Pattern CS " + paName + " SCN\n"); WriteLiteral("q {0:0.###} w", path.StrokeThickness); WriteGeometry(path.Data); WriteLiteral("S Q\n"); //// Create a FormXObject with a soft mask //PdfFormXObject form = LinearShadingBuilder.BuildFormFromLinearGradientBrush(Context, lgBrush, path.Data); //string foName = Resources.AddForm(form); //WriteLiteral(foName + " Do\n"); } else { PdfShadingPattern pattern = LinearShadingBuilder.BuildPatternFromLinearGradientBrush(Context, lgBrush, Transform); string paName = Resources.AddPattern(pattern); WriteLiteral("/Pattern CS " + paName + " SCN\n"); WriteLiteral("q {0:0.###} w", path.StrokeThickness); WriteGeometry(path.Data); WriteLiteral("S Q\n"); } } else if ((rgBrush = path.Stroke as RadialGradientBrush) != null) { // HACK WriteLiteral("/DeviceRGB CS 0 1 0 RG\n"); WriteLiteral("q {0:0.###} w", path.StrokeThickness); WriteGeometry(path.Data); WriteLiteral("S Q\n"); } else if ((iBrush = path.Stroke as ImageBrush) != null) { // HACK WriteLiteral("/DeviceRGB CS 0 1 0 RG\n"); WriteLiteral("q {0:0.###} w", path.StrokeThickness); WriteGeometry(path.Data); WriteLiteral("S Q\n"); } else if ((vBrush = path.Stroke as VisualBrush) != null) { // HACK WriteLiteral("/DeviceRGB CS 0 1 0 RG\n"); WriteLiteral("q {0:0.###} w", path.StrokeThickness); WriteGeometry(path.Data); WriteLiteral("S Q\n"); } else { Debug.Assert(false); } }
void RealizeLinearGradientBrush(LinearGradientBrush brush, XForm xform) { XMatrix matrix = currentTransform; PdfShadingPattern pattern = new PdfShadingPattern(writer.Owner); pattern.Elements[PdfShadingPattern.Keys.PatternType] = new PdfInteger(2); // shading pattern // Setup shading PdfShading shading = new PdfShading(writer.Owner); PdfColorMode colorMode = PdfColorMode.Rgb; //this.document.Options.ColorMode; PdfDictionary function = BuildShadingFunction(brush.GradientStops, colorMode); function.Elements.SetString("/@", "This is the shading function of a LinearGradientBrush"); shading.Elements[PdfShading.Keys.Function] = function; shading.Elements[PdfShading.Keys.ShadingType] = new PdfInteger(2); // Axial shading //if (colorMode != PdfColorMode.Cmyk) shading.Elements[PdfShading.Keys.ColorSpace] = new PdfName("/DeviceRGB"); //else //shading.Elements[Keys.ColorSpace] = new PdfName("/DeviceCMYK"); //double x1 = 0, y1 = 0, x2 = 0, y2 = 0; double x1 = brush.StartPoint.X; double y1 = brush.StartPoint.Y; double x2 = brush.EndPoint.X; double y2 = brush.EndPoint.Y; shading.Elements[PdfShading.Keys.Coords] = new PdfLiteral("[{0:0.###} {1:0.###} {2:0.###} {3:0.###}]", x1, y1, x2, y2); // old: Elements[Keys.Background] = new PdfRawItem("[0 1 1]"); // old: Elements[Keys.Domain] = shading.Elements[PdfShading.Keys.Extend] = new PdfLiteral("[true true]"); // Setup pattern pattern.Elements[PdfShadingPattern.Keys.Shading] = shading; pattern.Elements[PdfShadingPattern.Keys.Matrix] = PdfLiteral.FromMatrix(matrix); // new PdfLiteral("[" + PdfEncoders.ToString(matrix) + "]"); string name = writer.Resources.AddPattern(pattern); writer.WriteLiteral("/Pattern cs\n", name); writer.WriteLiteral("{0} scn\n", name); double alpha = brush.Opacity * brush.GradientStops.GetAverageAlpha(); if (alpha < 1 && writer.renderMode == RenderMode.Default) { #if true PdfExtGState extGState = writer.Owner.ExtGStateTable.GetExtGStateNonStroke(alpha); string gs = writer.Resources.AddExtGState(extGState); writer.WriteLiteral("{0} gs\n", gs); #else #if true if (xform == null) { PdfExtGState extGState = this.writer.Owner.ExtGStateTable.GetExtGStateNonStroke(alpha); string gs = this.writer.Resources.AddExtGState(extGState); this.writer.WriteGraphicState(extGState); } else { //PdfFormXObject pdfForm = this.writer.Owner.FormTable.GetForm(form); PdfFormXObject pdfForm = xform.pdfForm; pdfForm.Elements.SetString("/@", "This is the Form XObject of the soft mask"); string formName = this.writer.Resources.AddForm(pdfForm); PdfTransparencyGroupAttributes tgAttributes = new PdfTransparencyGroupAttributes(this.writer.Owner); //this.writer.Owner.Internals.AddObject(tgAttributes); tgAttributes.Elements.SetName(PdfTransparencyGroupAttributes.Keys.CS, "/DeviceRGB"); // Set reference to transparency group attributes pdfForm.Elements.SetObject(PdfFormXObject.Keys.Group, tgAttributes); pdfForm.Elements[PdfFormXObject.Keys.Matrix] = new PdfLiteral("[1.001 0 0 1.001 0.001 0.001]"); PdfSoftMask softmask = new PdfSoftMask(this.writer.Owner); this.writer.Owner.Internals.AddObject(softmask); softmask.Elements.SetString("/@", "This is the soft mask"); softmask.Elements.SetName(PdfSoftMask.Keys.S, "/Luminosity"); softmask.Elements.SetReference(PdfSoftMask.Keys.G, pdfForm); //pdfForm.Elements.SetName(PdfFormXObject.Keys.Type, "Group"); //pdfForm.Elements.SetName(PdfFormXObject.Keys.ss.Ss.Type, "Group"); PdfExtGState extGState = new PdfExtGState(this.writer.Owner); this.writer.Owner.Internals.AddObject(extGState); extGState.Elements.SetReference(PdfExtGState.Keys.SMask, softmask); this.writer.WriteGraphicState(extGState); } #else XForm form = new XForm(this.writer.Owner, 220, 140); XGraphics formGfx = XGraphics.FromForm(form); // draw something //XSolidBrush xbrush = new XSolidBrush(XColor.FromArgb(128, 128, 128)); XLinearGradientBrush xbrush = new XLinearGradientBrush(new XPoint(0, 0), new XPoint(220, 0), XColors.White, XColors.Black); formGfx.DrawRectangle(xbrush, -10000, -10000, 20000, 20000); //formGfx.DrawString("Text, Graphics, Images, and Forms", new XFont("Verdana", 10, XFontStyle.Regular), XBrushes.Navy, 3, 0, XStringFormat.TopLeft); formGfx.Dispose(); // Close form form.Finish(); PdfFormXObject pdfForm = this.writer.Owner.FormTable.GetForm(form); string formName = this.writer.Resources.AddForm(pdfForm); //double x = 20, y = 20; //double cx = 1; //double cy = 1; //this.writer.AppendFormat("q {2:0.###} 0 0 -{3:0.###} {0:0.###} {4:0.###} cm 100 Tz {5} Do Q\n", // x, y, cx, cy, y + 0, formName); //this.writer.AppendFormat("q {2:0.###} 0 0 -{3:0.###} {0:0.###} {4:0.###} cm 100 Tz {5} Do Q\n", // x, y, cx, cy, y + 220/1.5, formName); PdfTransparencyGroupAttributes tgAttributes = new PdfTransparencyGroupAttributes(this.writer.Owner); this.writer.Owner.Internals.AddObject(tgAttributes); tgAttributes.Elements.SetName(PdfTransparencyGroupAttributes.Keys.CS, "/DeviceRGB"); // Set reference to transparency group attributes pdfForm.Elements.SetReference(PdfFormXObject.Keys.Group, tgAttributes); PdfSoftMask softmask = new PdfSoftMask(this.writer.Owner); this.writer.Owner.Internals.AddObject(softmask); softmask.Elements.SetName(PdfSoftMask.Keys.S, "/Luminosity"); softmask.Elements.SetReference(PdfSoftMask.Keys.G, pdfForm); //pdfForm.Elements.SetName(PdfFormXObject.Keys.Type, "Group"); //pdfForm.Elements.SetName(PdfFormXObject.Keys.ss.Ss.Type, "Group"); PdfExtGState extGState = new PdfExtGState(this.writer.Owner); this.writer.Owner.Internals.AddObject(extGState); extGState.Elements.SetReference(PdfExtGState.Keys.SMask, softmask); this.writer.WriteGraphicState(extGState); #endif #endif } }
void RealizeRadialGradientBrush(RadialGradientBrush brush, XForm xform) { XMatrix matrix = new XMatrix(); // this.renderer.defaultViewMatrix; //matrix.MultiplyPrepend(this.Transform); matrix = currentTransform; //matrix.MultiplyPrepend(XMatrix.CreateScaling(1.3, 1)); PdfShadingPattern pattern = new PdfShadingPattern(writer.Owner); pattern.Elements[PdfShadingPattern.Keys.PatternType] = new PdfInteger(2); // shading pattern // Setup shading PdfShading shading = new PdfShading(writer.Owner); PdfColorMode colorMode = PdfColorMode.Rgb; //this.document.Options.ColorMode; PdfDictionary function = BuildShadingFunction(brush.GradientStops, colorMode); shading.Elements[PdfShading.Keys.ShadingType] = new PdfInteger(3); // Radial shading //if (colorMode != PdfColorMode.Cmyk) shading.Elements[PdfShading.Keys.ColorSpace] = new PdfName("/DeviceRGB"); //else //shading.Elements[Keys.ColorSpace] = new PdfName("/DeviceCMYK"); double x0 = brush.GradientOrigin.X; double y0 = brush.GradientOrigin.Y; double r0 = 0; double x1 = brush.Center.X; double y1 = brush.Center.Y; double r1 = brush.RadiusX; shading.Elements[PdfShading.Keys.Coords] = new PdfLiteral("[{0:0.###} {1:0.###} {2:0.###} {3:0.###} {4:0.###} {5:0.###}]", x0, y0, r0, x1, y1, r1); // old: Elements[Keys.Background] = new PdfRawItem("[0 1 1]"); // old: Elements[Keys.Domain] = shading.Elements[PdfShading.Keys.Function] = function; shading.Elements[PdfShading.Keys.Extend] = new PdfLiteral("[true true]"); // Setup pattern pattern.Elements[PdfShadingPattern.Keys.Shading] = shading; pattern.Elements[PdfShadingPattern.Keys.Matrix] = PdfLiteral.FromMatrix(matrix); // new PdfLiteral("[" + PdfEncoders.ToString(matrix) + "]"); string name = writer.Resources.AddPattern(pattern); writer.WriteLiteral("/Pattern cs\n", name); writer.WriteLiteral("{0} scn\n", name); double alpha = brush.Opacity * brush.GradientStops.GetAverageAlpha(); if (alpha < 1) { #if true PdfExtGState extGState = writer.Owner.ExtGStateTable.GetExtGStateNonStroke(alpha); string gs = writer.Resources.AddExtGState(extGState); writer.WriteLiteral("{0} gs\n", gs); #else if (xform == null) { PdfExtGState extGState = this.writer.Owner.ExtGStateTable.GetExtGStateNonStroke(alpha); string gs = this.writer.Resources.AddExtGState(extGState); this.writer.WriteGraphicState(extGState); } else { //PdfFormXObject pdfForm = this.writer.Owner.FormTable.GetForm(form); PdfFormXObject pdfForm = xform.pdfForm; pdfForm.Elements.SetString("/@", "This is the Form XObject of the soft mask"); string formName = this.writer.Resources.AddForm(pdfForm); PdfTransparencyGroupAttributes tgAttributes = new PdfTransparencyGroupAttributes(this.writer.Owner); //this.writer.Owner.Internals.AddObject(tgAttributes); tgAttributes.Elements.SetName(PdfTransparencyGroupAttributes.Keys.CS, "/DeviceRGB"); // Set reference to transparency group attributes pdfForm.Elements.SetObject(PdfFormXObject.Keys.Group, tgAttributes); pdfForm.Elements[PdfFormXObject.Keys.Matrix] = new PdfLiteral("[1.001 0 0 1.001 0.001 0.001]"); PdfSoftMask softmask = new PdfSoftMask(this.writer.Owner); this.writer.Owner.Internals.AddObject(softmask); softmask.Elements.SetString("/@", "This is the soft mask"); softmask.Elements.SetName(PdfSoftMask.Keys.S, "/Luminosity"); softmask.Elements.SetReference(PdfSoftMask.Keys.G, pdfForm); //pdfForm.Elements.SetName(PdfFormXObject.Keys.Type, "Group"); //pdfForm.Elements.SetName(PdfFormXObject.Keys.ss.Ss.Type, "Group"); PdfExtGState extGState = new PdfExtGState(this.writer.Owner); this.writer.Owner.Internals.AddObject(extGState); extGState.Elements.SetReference(PdfExtGState.Keys.SMask, softmask); this.writer.WriteGraphicState(extGState); } #endif } }
public ShadingColor(PdfShadingPattern shadingPattern) : base(TYPE_SHADING, .5f, .5f, .5f) { PdfShadingPattern = shadingPattern; }