如何在iTextSharp中绘制垂直渐变?

4

我正在尝试在iTextSharp pdf文档底部绘制垂直渐变:

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();

这将在我想要创建的确切位置创建一个渐变,但渐变是从左侧(白色)到右侧(绿色)的水平渐变。

我希望渐变是从顶部(白色)到底部(绿色)的垂直渐变。

修改坐标,就像某人在这里所做的那样 (Does iTextsharp support multi color diagonal gradients?),没有解决问题。我还尝试旋转文档,但也不起作用。

1个回答

1
您正在使用错误的坐标。在Java中,您需要像这样做:
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();
}

请查看从上到下的渐变以获取完整的示例代码。

你看到了区别吗?

  • 你从左上角(0,document.PageSize.Height)到右下角(document.PageSize.Width,0)。这是一个对角线。
  • 你想要从顶部(0,document.PageSize.Height)到底部(0,0),结果如下:gradient_top_to_bottom.pdf

enter image description here


明白了,非常感谢。需要做一些调整,不使用全高度...但无论如何,就是这样。 - Norman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接