【问题标题】:How do I make an image not selectable如何使图像无法选择
【发布时间】:2021-01-15 03:35:10
【问题描述】:

我已将图像添加到我的 iTextSharp PDF 文档中,如下所示:

Public Sub CreatePDFFromBitmap(ByVal uPath As String, ByVal uBitmap As Bitmap)

    Dim nFs As System.IO.FileStream = New FileStream(uPath, FileMode.Create)

    Dim nDocument As iTextSharp.text.Document
    Dim nWriter As iTextSharp.text.pdf.PdfWriter
    Dim nCb As iTextSharp.text.pdf.PdfContentByte

    Dim nImgFromBitmap As System.Drawing.Image = DirectCast(uBitmap, System.Drawing.Image)

    Dim nImg As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(nImgFromBitmap, Imaging.ImageFormat.Png)
    Dim bLandscape As Boolean = (nImg.Width > nImg.Height)

    'rotation needs to be set before document is being opened
    If bLandscape Then
        nDocument = New iTextSharp.text.Document(PageSize.A4.Rotate, 0, 0, 0, 0)
    Else
        nDocument = New iTextSharp.text.Document(PageSize.A4, 0, 0, 0, 0)
    End If

    'if an exception is raised here, the following will help:  https://stackoverflow.com/questions/15833285/pdfwriter-getinstance-throws-system-nullreferenceexception
    nWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(nDocument, nFs)

    nDocument.Open()

    nCb = nWriter.DirectContent

    nImg.ScaleToFit(nDocument.PageSize.Width, nDocument.PageSize.Height) 'raises dpi size :-)))

    'X-Y-Koordinatensystem 0,0 startet also unten links, nicht oben-links
    nImg.SetAbsolutePosition(0, nDocument.PageSize.Height - nImg.ScaledHeight)
    nCb.AddImage(nImg)

    nDocument.Close()
    nWriter.Close()
    nFs.Close()

End Sub

它工作正常。 但是,当我单击 PDF 中的图像时,它会被选中。 这不是我想要的。 如果我单击 PDF 中的图像,它不应该被选中。

这就是它的样子:图像变成蓝色:

我想在 PDF 中添加可编辑字段,所以我需要使图像不可选择,否则会混淆用户。

【问题讨论】:

    标签: vb.net itext


    【解决方案1】:

    正如 Abdel-Rahman Al-Qawasmi 在他的回答中提到的,它完全取决于 PDF 查看器选择哪些实体,哪些不可选。因此,没有保证可以得到你想要的东西。

    尽管如此,还是有一些方法可以将图像放入 PDF 中,这会阻止大多数 PDF 查看器的当前版本使其可选择。这些方法要么将位图图像转换为非位图实体(例如,通过迭代位图的像素并使用矢量图形为每个像素绘制一个小矩形)或包装位图图像 进入通常无法选择的内容。

    让我们采用后一种方法,将图像包装成页面大小的 PDF 模式,然后用它填充实际页面。您可以通过更换您的

    nCb.AddImage(nImg)
    

    通过

    Dim painter As iTextSharp.text.pdf.PdfPatternPainter = nCb.CreatePattern(nDocument.PageSize.Width, nDocument.PageSize.Height)
    painter.AddImage(nImg)
    
    nCb.SetColorFill(New iTextSharp.text.pdf.PatternColor(painter))
    nCb.Rectangle(0, 0, nDocument.PageSize.Width, nDocument.PageSize.Height)
    nCb.Fill()
    

    (这本质上是来自this answer 的Java/iText 代码的VB/iTextSharp 挂件。)

    【讨论】:

    • 非常感谢这个聪明的解决方案,你真的帮了我很多!
    【解决方案2】:

    这是一个pdf程序规范,与asp.net或vb.net编程无关。您需要控制 pdf 阅读器设置。或者尝试使用其他格式。

    【讨论】:

    • 虽然严格来说你是对的,但有一些方法可以阻止 PDF 查看器选择材料;不一定一直工作,显然不能保证将来工作,但对于 OP 来说可能就足够了。
    猜你喜欢
    • 2016-10-29
    • 2021-10-29
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多