更改使用 PyPDF2 创建的矩形 link 轮廓的颜色

Change color of rectangle link contourn created with PyPDF2

我想改变用 PyPDF2 addLink 命令创建的矩形轮廓的颜色 从黑色到蓝色 但我找不到关于它的文档,我还没有找到任何解决方案。

from PyPDF2 import PdfFileWriter
from pathlib import Path


output = PdfFileWriter()
output.addBlankPage(width=72, height=72) #page 1 with index 0
output.addBlankPage(width=72, height=72) #page 2 with index 1
output.addLink(0, 1, [10, 10, 50, 30], border=[0, 0, 1])

with Path("link_example.pdf").open(mode="wb") as output_file:
    output.write(output_file)

我得到的唯一信息是评论的自我解释:“边框:如果提供,一个描述边框绘制属性的数组。有关详细信息,请参阅 PDF 规范。如果省略此参数,则不会绘制边框."

经过大量研究,我发现使用原始 PyPDF2 代码无法更改轮廓的颜色。出于这个原因,我对它进行了一些修改,以便在 RGB 中允许一个额外的颜色参数。

我已经更改了 ..PythonXX/Lib/PyPDF2 中文件 pdf.py 的函数 addLink 以包含参数 color

def addLink(self, pagenum, pagedest, rect, border=None, color=None, fit='/Fit', *args):
    """
    Add an internal link from a rectangular area to the specified page.

    :param int pagenum: index of the page on which to place the link.
    :param int pagedest: index of the page to which the link should go.
    :param rect: :class:`RectangleObject<PyPDF2.generic.RectangleObject>` or array of four
        integers specifying the clickable rectangular area
        ``[xLL, yLL, xUR, yUR]``, or string in the form ``"[ xLL yLL xUR yUR ]"``.
    :param border: if provided, an array describing border-drawing
        properties. See the PDF spec for details. No border will be
        drawn if this argument is omitted.
    :param color: if provided, an array describing border-color
        RGB. See the PDF spec for details. Black if this argument is omitted.
    :param str fit: Page fit or 'zoom' option (see below). Additional arguments may need
        to be supplied. Passing ``None`` will be read as a null value for that coordinate.

    Valid zoom arguments (see Table 8.2 of the PDF 1.7 reference for details):
         /Fit       No additional arguments
         /XYZ       [left] [top] [zoomFactor]
         /FitH      [top]
         /FitV      [left]
         /FitR      [left] [bottom] [right] [top]
         /FitB      No additional arguments
         /FitBH     [top]
         /FitBV     [left]
    """

    pageLink = self.getObject(self._pages)['/Kids'][pagenum]
    pageDest = self.getObject(self._pages)['/Kids'][pagedest]  # TODO: switch for external link
    pageRef = self.getObject(pageLink)

    if border is not None:
        borderArr = [NameObject(n) for n in border[:3]]
        if len(border) == 4:
            dashPattern = ArrayObject([NameObject(n) for n in border[3]])
            borderArr.append(dashPattern)
    else:
        borderArr = [NumberObject(0)] * 3

    if color is not None:
        colorArr = [NameObject(n) for n in color[:3]]
    else:
        colorArr = [NumberObject(0)] * 3

    if isString(rect):
        rect = NameObject(rect)
    elif isinstance(rect, RectangleObject):
        pass
    else:
        rect = RectangleObject(rect)

    zoomArgs = []
    for a in args:
        if a is not None:
            zoomArgs.append(NumberObject(a))
        else:
            zoomArgs.append(NullObject())
    dest = Destination(NameObject("/LinkName"), pageDest, NameObject(fit),
                       *zoomArgs)  # TODO: create a better name for the link
    destArray = dest.getDestArray()

    lnk = DictionaryObject()
    lnk.update({
        NameObject('/Type'): NameObject('/Annot'),
        NameObject('/Subtype'): NameObject('/Link'),
        NameObject('/P'): pageLink,
        NameObject('/Rect'): rect,
        NameObject('/Border'): ArrayObject(borderArr),
        NameObject('/C'): ArrayObject(colorArr),
        NameObject('/Dest'): destArray
    })
    lnkRef = self._addObject(lnk)

    if "/Annots" in pageRef:
        pageRef['/Annots'].append(lnkRef)
    else:
        pageRef[NameObject('/Annots')] = ArrayObject([lnkRef])

_valid_layouts = ['/NoLayout', '/SinglePage', '/OneColumn', '/TwoColumnLeft', '/TwoColumnRight', '/TwoPageLeft',
                  '/TwoPageRight']

现在我可以得到一个蓝色轮廓,只需在函数中包含新参数:

from PyPDF2 import PdfFileWriter
from pathlib import Path


output = PdfFileWriter()
output.addBlankPage(width=72, height=72) #page 1 with index 0
output.addBlankPage(width=72, height=72) #page 2 with index 1
output.addLink(0, 1, [10, 10, 50, 30], border=[0, 0, 1], color=[0, 0, 1])

with Path("link_example.pdf").open(mode="wb") as output_file:
    output.write(output_file)