How to draw vertical gradient in iTextSharp?
I am trying to draw a vertical gradient at the bottom of an iTextSharp pdf document:
PdfShading shading = PdfShading.SimpleAxial(pdfWriter, 0, document.PageSize.Height, document.PageSize.Width, 0, BaseColor.WHITE, BaseColor.GREEN); PdfShadingPattern pattern = new PdfShadingPattern(shading); pdfContentByte.SetShadingFill(pattern); pdfContentByte.Rectangle(0, 0, document.PageSize.Width, 70); pdfContentByte.Fill();
Posted on StackOverflow on Dec 23, 2015 by Norman
You are using the wrong coordinates. In Java, you'd need something like this:
public void createPdf(String dest) throws IOException, DocumentException {
Rectangle pageSize = new Rectangle(150, 300);
Document document = new Document(pageSize);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
PdfShading shading = PdfShading.simpleAxial(writer,
0, pageSize.getHeight(),
0, 0,
BaseColor.WHITE, BaseColor.GREEN);
PdfShadingPattern pattern = new PdfShadingPattern(shading);
PdfContentByte canvas = writer.getDirectContent();
canvas.setShadingFill(pattern);
canvas.rectangle(0, 0, pageSize.getWidth(), pageSize.getHeight());
canvas.fill();
document.close();
}
See GradientTopToBottom for the full sample code.
Do you see the difference?
-
You go from the left-top corner (
0, document.PageSize.Height
) to the right-bottom corner (document.PageSize.Width, 0
). That's a diagonal. -
You want to go from the top (
0, document.PageSize.Height
) to the bottom (0, 0
) which leads to the following result: gradient_top_to_bottom.pdfGradient from top to bottom