Skip to content

Commit

Permalink
opener: make get_fileaccess() a standalone function
Browse files Browse the repository at this point in the history
FPDF_FILEACCESS structs are used for more than just
FPDF_LoadCustomDocument().
  • Loading branch information
mara004 committed Oct 12, 2022
1 parent 950db18 commit cc0c2b6
Showing 1 changed file with 12 additions and 27 deletions.
39 changes: 12 additions & 27 deletions src/pypdfium2/_helpers/_opener.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,14 @@
)


class BufferDataHolder:
class _data_holder:

def __init__(self, reader_func, buffer):
self.reader_func = reader_func
self.buffer = buffer
def __init__(self, *args):
self._args = args

def close(self):
id(self.reader_func)
id(self.buffer)


class ByteDataHolder:

def __init__(self, bytedata):
self.bytedata = bytedata

def close(self):
id(self.bytedata)
for arg in self._args:
id(arg)


class _reader_class:
Expand All @@ -46,7 +36,7 @@ def is_input_buffer(maybe_buffer):
return all( callable(getattr(maybe_buffer, a, None)) for a in ("seek", "tell", "read", "readinto") )


def open_pdf_buffer(buffer, password=None):
def get_fileaccess(buffer):

buffer.seek(0, 2)
file_len = buffer.tell()
Expand All @@ -57,16 +47,9 @@ def open_pdf_buffer(buffer, password=None):
fileaccess.m_GetBlock = get_functype(pdfium.FPDF_FILEACCESS, "m_GetBlock")( _reader_class(buffer) )
fileaccess.m_Param = None

pdf = pdfium.FPDF_LoadCustomDocument(fileaccess, password)
ld_data = BufferDataHolder(fileaccess.m_GetBlock, buffer)
ld_data = _data_holder(fileaccess.m_GetBlock, buffer)

return pdf, ld_data


def open_pdf_bytes(bytedata, password=None):
pdf = pdfium.FPDF_LoadMemDocument64(bytedata, len(bytedata), password)
ld_data = ByteDataHolder(bytedata)
return pdf, ld_data
return fileaccess, ld_data


def open_pdf(input_data, password=None):
Expand All @@ -78,9 +61,11 @@ def open_pdf(input_data, password=None):
if isinstance(input_data, str):
pdf = pdfium.FPDF_LoadDocument(input_data.encode("utf-8"), password)
elif isinstance(input_data, bytes):
pdf, ld_data = open_pdf_bytes(input_data, password)
pdf = pdfium.FPDF_LoadMemDocument64(input_data, len(input_data), password)
ld_data = _data_holder(input_data)
elif is_input_buffer(input_data):
pdf, ld_data = open_pdf_buffer(input_data, password)
fileaccess, ld_data = get_fileaccess(input_data)
pdf = pdfium.FPDF_LoadCustomDocument(fileaccess, password)
else:
raise TypeError("Invalid input type '%s'" % type(input_data).__name__)

Expand Down

0 comments on commit cc0c2b6

Please sign in to comment.