2
2
PDF: PDF image loader
3
3
'''
4
4
5
- try :
6
- from PIL import Image as PILImage
7
- except :
8
- raise
9
-
10
5
from kivy .cache import Cache
11
6
from kivy .logger import Logger
12
7
from kivy .core .image import ImageLoaderBase , ImageData , ImageLoader
13
8
14
- from kivy .graphics .texture import Texture , TextureRegion
9
+ from kivy .graphics .texture import Texture
15
10
Debug = False
16
11
17
12
import io
18
13
from pyPdf import PdfFileWriter , PdfFileReader
19
14
import PythonMagick as pm
15
+ import pygame
16
+
20
17
21
18
class ImageLoaderPDF (ImageLoaderBase ):
22
19
'''Image loader for PDF'''
@@ -33,35 +30,46 @@ def extensions():
33
30
def load (self , filename ):
34
31
try :
35
32
print "load pdf!" , self .page
33
+
36
34
# first extract the page from the pdf
37
- pdf = PdfFileReader (open (filename , 'rb' ))
38
- p = pdf .getPage (self .page )
39
- size = p .mediaBox [2 :]
40
- print p .trimBox , p .mediaBox , p .cropBox , p .bleedBox , p .artBox
35
+ with open (filename , 'rb' ) as fd :
36
+ pdf = PdfFileReader (fd )
37
+ page = pdf .getPage (self .page )
41
38
42
- w = PdfFileWriter ()
43
- w .addPage (p )
44
- f = io .BytesIO ()
45
- w .write (f )
46
- f .seek (0 )
39
+ pfw = PdfFileWriter ()
40
+ pfw .addPage (page )
41
+ f = io .BytesIO ()
42
+ pfw .write (f )
43
+ f .seek (0 )
47
44
48
45
# then convert the one page pdf filebuffer to an image
49
46
blob = pm .Blob (f .read ())
50
- blobrgb = pm .Blob ()
51
- pm .Image (blob ).write (blobrgb ,'rgba' )
52
- #blobpng.data
47
+ blobresult = pm .Blob ()
48
+
49
+ # export as a png. raw rgb/rgba might output interlaced/depth that
50
+ # we don't want. current PythonMagick bindings don't allow to change
51
+ # it. so rely as a png.
52
+ pmi = pm .Image (blob )
53
+ pmi .write (blobresult , 'png' )
53
54
54
- im = PILImage .frombuffer (
55
- 'RGBA' ,
56
- (size [0 ] * 2 , size [1 ]),
57
- blobrgb .data ).resize (size )
55
+ # load the png though pygame
56
+ fd = io .BytesIO ()
57
+ fd .write (blobresult .data )
58
+ fd .seek (0 )
59
+ im = pygame .image .load (fd , 'bleh.png' )
60
+ assert (im .get_bytesize () == 3 )
61
+
62
+ # update internals
63
+ self .filename = filename
64
+ data = pygame .image .tostring (im , 'RGB' , True )
65
+
66
+ # result a list of one image available
67
+ return [ImageData (im .get_width (), im .get_height (), 'rgb' , data )]
58
68
59
69
except :
60
70
Logger .warning ('Image: Unable to load image <%s>' % filename )
61
71
raise
62
72
63
- return (ImageData (size [0 ], size [1 ], 'rgba' , im .tostring ()),)
64
-
65
73
def populate (self ):
66
74
self ._textures = []
67
75
if __debug__ :
0 commit comments