【问题标题】:How can I rotate an image before adding it to a PDF?如何在将图像添加到 PDF 之前旋转图像?
【发布时间】:2020-04-28 14:47:43
【问题描述】:

我正在尝试向我的 PDF 的每一页添加多个随机动态水印图像。这些生成的图像应旋转 45 度。当我将图像添加到 PDF 时,即使指定了旋转,图像仍然显得平坦。任何想法为什么不应用旋转?我正在使用 Itext7

iText.Kernel.Geom.Rectangle pagesize;
Image img = DrawText(watermark);
ImageData imageData = ImageDataFactory.CreatePng(ImageToByteArray(img));

float x, y;
// loop over every page
for (int i = 1; i <= n; i++)
{
    int watermarksPerPage = GetRandomNumber(1, MAX_WATERMARKS_PER_PAGE);
    PdfPage page = doc.GetPage(i);
    pagesize = page.GetPageSizeWithRotation();
    PdfCanvas canvas = new PdfCanvas(page);

    x = (pagesize.GetLeft() + pagesize.GetRight());
    y = (pagesize.GetRight() + pagesize.GetBottom());

    canvas.SetExtGState(gs1);

    int boundaryWidth = (int)(x * INVISIBLE_BOUNDARY_PERCENT);
    int boundaryHeight = (int)(y * INVISIBLE_BOUNDARY_PERCENT);

    for (int m = 0; m <= watermarksPerPage; m++)
    {
        //create an invisble boudary that the watermark should not cross using x% of width      
        float newx = GetRandomNumber(0, (int)x - boundaryHeight);
        float newy = GetRandomNumber(0, (int)y - boundaryWidth);
        imageData.SetRotation(ROTATION);
        canvas.AddImage(imageData, newx, newy, false);
    }
}

【问题讨论】:

    标签: c# .net-core itext itext7


    【解决方案1】:

    ImageData.SetRotation 不会设置每当这个ImageData 实例由 iText 呈现时使用的旋转值,它只是覆盖图像的元数据,指示图像应该如何呈现为直立。据我所知,iText 代码当前根本没有调用相应的GetRotation,因此忽略了您的旋转值。

    因此,无需设置该图像数据旋转值,只需在插入图像之前旋转画布,例如像这样:

    canvas.SaveState();
    canvas.ConcatMatrix(AffineTransform.GetRotateInstance(Math.PI / 4, x, y));
    canvas.AddImage(imageData, x - imageData.GetWidth() / 2, y - imageData.GetHeight() / 2, false);
    canvas.RestoreState();
    

    【讨论】:

    • 谢谢它的工作!我只需要调整一些东西,但图像肯定出现了旋转。
    猜你喜欢
    • 2018-10-07
    • 2015-06-29
    • 2021-03-23
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    • 2013-04-04
    相关资源
    最近更新 更多