def image2Pdf(folder: str, img: str, outputPath: str = None) -> str: """ Converts an image to a pdf in A4 format. Does not support HEIC format. Arguments: folder: string, path where image is stored. img: string, name of image. Should include file extension. outputPath: string, optional, path to directory where pdf should be stored. Returns: Path to resulting pdf as string. """ imgName = img[:img.rfind(".")] if outputPath: imgPdf = f"{outputPath}/{imgName}.pdf" else: imgPdf = f"{imgName}.pdf" imgPath = os.path.join(folder, img) # Delete alpha channel by converting to RGB. Save as temp file. with Image.open(imgPath) as img: img = img.convert('RGB') width, height = img.size img.save('temp.jpeg', format='JPEG') # Determine orientation of the image and set pdf size accordingly if width < height: a4Size = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297)) else: a4Size = (img2pdf.mm_to_pt(297), img2pdf.mm_to_pt(210)) layout = img2pdf.get_layout_fun(a4Size) # Convert the image to pdf, delete temp file. pdfBytes = img2pdf.convert('temp.jpeg', layout_fun=layout) with open(imgPdf, 'wb') as fout: fout.write(pdfBytes) os.remove('temp.jpeg') return imgPdf
def pack_to_pdf(dir_name): a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297)) layout_fun = img2pdf.get_layout_fun(a4inpt) file_list = list() for root, dirs, files in os.walk(dir_name): for file in files: if file.endswith('.jpg'): pathname1 = os.path.join(root, file) file_list.append(pathname1) file_lis_list = list() while file_list: try: file_lis_list.append(file_list[:501]) del file_list[:501] except IndexError: file_lis_list.append(file_list[:-1]) del file_list[::] for index, item in enumerate(file_lis_list): try: with open('{}/{}.pdf'.format(dir_name, index + 1), 'wb') as f: f.write(img2pdf.convert(item, layout_fun=layout_fun)) except Exception as e: print(e.args) print('第{}个打包失败~~┭┮﹏┭┮~~'.format(index + 1)) else: print('第{}个打包成功<(* ̄▽ ̄*)/!'.format(index + 1))
def main(path, new_path): images_dir = "D:/temp/" pdf_file = open(path, "rb") pdf = PyPDF2.PdfFileReader(pdf_file, strict=False) num = pdf.getNumPages() new_pages = -1 if num < 10: new_pages = 1 elif num > 100: new_pages = 10 elif num > 500: return None else: new_pages = int(num / 10) pdf_file.close() image_paths = [] # with convert_from_path(path) as images: images = convert_from_path(path) # print(images,type(images)) for index, image in enumerate(images): if index >= new_pages: break else: image_path = images_dir + str(index) + ".jpg" image.save(image_path) image_paths.append(image_path) a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297)) layout_fun = img2pdf.get_layout_fun(a4inpt) with open(new_path, 'wb') as f: f.write(img2pdf.convert(image_paths, layout_fun=layout_fun))
def split_pdf(start=2, end=4, name="report2013_1.pdf"): path = r"C:\pdfs\0205\report2013.pdf" images_dir = r"C:\pdfs\0205" # pdf_file = open(path, "rb") # pdf = PyPDF2.PdfFileReader(pdf_file, strict=False) # num = pdf.getNumPages() # new_pages = -1 # if num < 10: # new_pages = 1 # elif num > 100: # new_pages = 10 # elif num > 500: # return None # else: # new_pages = int(num / 10) # pdf_file.close() # image_paths = [] # with convert_from_path(path) as images: images = convert_from_path(path) # print(images,type(images)) image_paths = [] new_path = os.path.join(images_dir, name) for index, image in enumerate(images): if index > start and index <= end: image_path = images_dir + str(index) + ".jpg" image.save(image_path) image_paths.append(image_path) a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297)) layout_fun = img2pdf.get_layout_fun(a4inpt) with open(new_path, 'wb') as f: f.write(img2pdf.convert(image_paths, layout_fun=layout_fun))
def img_pdf(self): """ :return: converts images to pdf """ a4 = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297)) layout_fun = img2pdf.get_layout_fun(a4) img = [] temp_img = [] src = Path(self.src) temp_dir = tempfile.mkdtemp() count = 0 ext_ = ["*.png", "*.jpg", "*.jpeg"] with open(str(self.dst), "wb") as f: for ext in ext_: for file in src.rglob(ext): img.append(str(file)) with Path(temp_dir) as tm_dir: for file in img: im = Image.open(str(file)) rgba_im = im.convert('RGBA') rgb = rgba_im.convert("RGB") rgb.convert('RGB').save(str(f'{tm_dir}/{count}.jpg')) count += 1 for t_img in tm_dir.rglob('*.jpg'): temp_img.append(str(t_img)) f.write(img2pdf.convert(temp_img, layout_fun=layout_fun)) shutil.rmtree(temp_dir)
def render_wp_image_net_real_size(vertical, horizon, high, theta, save_path, simage): tmp_box = ".tmp/save_box.svg" tmp_box_pdf = ".tmp/save_box.pdf" tmp_wrap_pdf = ".tmp/save_wrap.pdf" out = render_net_real_size(vertical, horizon, high, theta, tmp_box, flag=1) buffer = QBuffer() buffer.open(QBuffer.ReadWrite) simage.save(buffer, "PNG") pil_im = Image.open(io.BytesIO(buffer.data())) pil_im = pil_im.convert("RGB") # print("pil size: ", pil_im.size) pil_im.save(".tmp/save_wrap_paper.png") drawing = svg2rlg(tmp_box) renderPDF.drawToFile(drawing, tmp_box_pdf) output_s = (img2pdf.mm_to_pt(out[0]), img2pdf.mm_to_pt(out[1])) layout_fun = img2pdf.get_layout_fun(output_s) # print("saved: ", Image.open(".tmp/save_wrap_paper.png").size) try: with open(tmp_wrap_pdf, "wb") as f: f.write( img2pdf.convert(".tmp/save_wrap_paper.png", layout_fun=layout_fun)) except OSError: print("file is Opening") merger = PyPDF2.PdfFileMerger() merger.append(tmp_box_pdf) merger.append(tmp_wrap_pdf) merger.write(save_path) merger.close() os.remove(tmp_box) os.remove(tmp_box_pdf) os.remove(tmp_wrap_pdf) os.remove(".tmp/save_wrap_paper.png")
def all_pictures2pdf(path: str, fixed_size: bool = False) -> None: # specify paper size (A4) a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297)) layout_fun = img2pdf.get_layout_fun(a4inpt, auto_orient=True) if fixed_size else img2pdf.get_layout_fun( auto_orient=True) for pic_name in get_picture_names(path): pdf_name = pic_name.split(".")[-1] + ".pdf" with open(pdf_name, "wb") as pdf: pdf.write(img2pdf.convert(pic_name, layout_fun=layout_fun))
def __init__(self, path, url='http://10.7.0.100:3000/convert/office'): self.path = path self.file = Path(path) self.temp_dir = tempfile.TemporaryDirectory() if not self.file.exists() or not self.file.is_file(): raise PrinterFileException("File does not exist") self.name = self.file.name self.extension = self.name.split('.')[-1].lower() supported_extensions = ["pdf", "png", "jpg"] + self.office_extensions if self.extension not in supported_extensions: raise PrinterFileException( f"File extension {self.extension} is not supported") if self.extension == "pdf": self.file_type = 'pdf' self.pdf_path = path self.load_pdf() if self.pdf.isEncrypted: raise PrinterFileException("Encrypted pdf`s are not supported") elif self.extension == 'png': self.file_type = 'png' # specify paper size (A4) a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297)) layout_fun = img2pdf.get_layout_fun(a4inpt) with Image.open(self.path) as png: png.load() background = Image.new("RGB", png.size, (255, 255, 255)) background.paste(png, mask=png.split()[3]) # 3 is the alpha channel jpg_path = f'{self.temp_dir.name}/{random_string()}.jpg' self.pdf_path = f'{self.temp_dir.name}/{random_string()}.pdf' background.save(jpg_path, 'JPEG', quality=80) with open(self.pdf_path, "wb") as f: f.write(img2pdf.convert(f'{jpg_path}', layout_fun=layout_fun)) f.close() self.load_pdf(self.pdf_path) elif self.extension == 'jpg': self.file_type = 'jpg' self.pdf_path = f'{self.temp_dir.name}/{random_string()}.pdf' # specify paper size (A4) a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297)) layout_fun = img2pdf.get_layout_fun(a4inpt) with open(self.pdf_path, "wb") as f: f.write(img2pdf.convert(f'{self.path}', layout_fun=layout_fun)) f.close() self.load_pdf(self.pdf_path) elif self.extension in self.office_extensions: self.file_type = self.extension r = requests.post(url, files={'input.docx': open(self.path, 'rb')}) if r.status_code != 200: raise PrinterFileException( f"Conversion error. HTTP code {r.status_code}") self.pdf_path = f'{self.temp_dir.name}/{random_string()}.pdf' with open(self.pdf_path, 'wb') as binary_file: binary_file.write(r.content) binary_file.close() self.load_pdf(self.pdf_path)
def file_opener(self): input = filedialog.askopenfilenames(initialdir="/", title = "Select Image") file_name = os.path.join(filedialog.askdirectory(), str(datetime.datetime.now().date()).replace('-', '')+'_'+ str(datetime.datetime.now().time()).replace(':','').replace('.', '')+'.pdf') try: with open(file_name, 'wb') as f: layout = img2pdf.get_layout_fun((img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297))) f.write(img2pdf.convert(list(input), layout_fun = layout)) messagebox.showinfo("info",'Successfully Saved at '+file_name) except: messagebox.showerror("Error", 'Could not convert')
def album2pdf(): albums = os.listdir(save_path) album_cover = albums.pop() albums.insert(0, album_cover) albums = [os.path.join(save_path, album) for album in albums] remove_transparent(albums) a4inpt = (img2pdf.mm_to_pt(720), img2pdf.mm_to_pt(1080)) layout_fun = img2pdf.get_layout_fun(a4inpt) with open('mi10years.pdf', 'wb') as f: f.write(img2pdf.convert(albums, layout_fun=layout_fun))
def from_photo_to_pdf(photo_path): # 1、生成地址列表 photo_list = os.listdir(photo_path) photo_list = [os.path.join(photo_path, i) for i in photo_list] # 1、指定pdf的单页的宽和高 # A4纸张 # a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297)) # 我的自定义: a4inpt = (img2pdf.mm_to_pt(720), img2pdf.mm_to_pt(1080)) layout_fun = img2pdf.get_layout_fun(a4inpt) with open(photo_path + '\\1result.pdf', 'wb') as f: f.write(img2pdf.convert(photo_list, layout_fun=layout_fun))
def render_to_pdf(self): print("Rendering to PDF...") a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297)) layout_fun = img2pdf.get_layout_fun(a4inpt) with open(f"{self.save_path}/bulletin.pdf", "wb") as f: f.write( img2pdf.convert([ i.path for i in os.scandir(self.save_path) if i.name.endswith(".jpg") ], dpi=150, layout_fun=layout_fun)) print("Succesfully rendered PDF...")
def save_as_pdf(self, pages): print('combine to one pdf...') a4 = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297)) layout_fun_a4 = img2pdf.get_layout_fun(pagesize=a4) image_names = [ str(Path('scans') / page.processed_filename) for page in pages if not page.removed ] with open(Path('scans') / f'{self.config.name}.pdf', "wb") as f: f.write( img2pdf.convert(image_names, layout_fun=layout_fun_a4, viewer_center_window=True))
def join_pdf(work_path): with open(work_path + '\\' + 'setting.yml', 'r') as yml: setting = yaml.safe_load(yml) myfilelist2 = [] for files in os.listdir(work_path): if (files[-4:] == '.jpg' and files[:4] == 'PDF_'): filepath = os.path.join(work_path, files) myfilelist2.append(filepath) # layout_ = img2pdf.get_layout_fun('1283,1692') a4inpt = (img2pdf.mm_to_pt(setting['pagesize']['wide']), img2pdf.mm_to_pt(setting['pagesize']['heigh'])) layout_ = img2pdf.get_layout_fun(a4inpt) with open(work_path + '\\' + setting['pdffilename'], "wb") as aPDF: aPDF.write(img2pdf.convert(myfilelist2, layout_fun=layout_))
def from_photo_to_pdf(photo_path): # 1、生成地址列表 photo_list = os.listdir(photo_path) photo_list = [os.path.join(photo_path,i) for i in photo_list] # 1、指定pdf的单页的宽和高 # A4纸张 # a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297)) # 我的自定义: a4inpt = (img2pdf.mm_to_pt(720), img2pdf.mm_to_pt(1080)) layout_fun = img2pdf.get_layout_fun(a4inpt) save_name = photo_path.split("\\")[-1]+'.pdf' with open(save_name, 'wb') as f: f.write(img2pdf.convert(photo_list, layout_fun=layout_fun))
def convert2pdf_func(self): cropped_images = os.listdir('./Cropped_images/') i = 0 for image in cropped_images: cropped_images[i] = './Cropped_images/' + cropped_images[i] i += 1 cropped_images.sort() if self.check_a4 == True: a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297)) layout_fun = img2pdf.get_layout_fun(a4inpt) with open('./Cropped_images.pdf', 'wb') as f: f.write(img2pdf.convert(cropped_images, layout_fun=layout_fun)) else: with open('./Cropped_images.pdf', 'wb') as f: f.write(img2pdf.convert(cropped_images))
def ImageToPdf(outputpath, imagepath): ''' outputpath: pathlib.Path() imagepath: pathlib.Path() ''' lists = list(imagepath.glob("**/*")) # 単フォルダ内を検索 print(outputpath, imagepath) a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297)) layout_fun = img2pdf.get_layout_fun(a4inpt) imgpath_str = str(imagepath) # Pathlib.WindowsPath()をstring型に変換しないとエラー files = [str(i) for i in lists if i.match("*.jpg") or i.match("*.png")] imgdata = [Image.open(img) for img in files] print(len(imgdata)) imgs = [] # 最終的な画像のファイル名。中間ファイル。 cur = 0 while True: width = 400 # 1問の最大サイズ程度に height = 500 # 1問の最大サイズ程度に # ベースとなる画像の定義 img = Image.new('RGB', size=(width * 3, height * 3), color="white") # 3x3につなげる。 for i in range(3): for j in range(3): if cur >= len(imgdata): continue img_read = imgdata[cur] w, h = calc_center(width, height, img_read) img.paste(img_read, (i * width + w, j * height + h)) cur += 1 filename = imgpath_str + os.sep + "tmp_{}.png".format(cur) print(filename) img.save(filename) imgs.append(filename) if cur >= len(imgdata): break data = img2pdf.convert(imgs, layout_fun=layout_fun) # 書き込み with open(outputpath, "wb") as f: f.write(data) print(outputpath.name + " :Done") # 中間ファイルを消す for filename in imgs: print("remove : ", filename) os.remove(filename)
def img_pdf(nome): # A4 a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297)) layout_fun = img2pdf.get_layout_fun(a4inpt) dirname = str(os.path.abspath(os.path.dirname(__file__)) + f"/{nome}") with open(f"{nome}.pdf", "wb") as f: imgs = [] for fname in os.listdir(dirname): if not fname.endswith(".png"): continue path = os.path.join(dirname, fname) if os.path.isdir(path): continue imgs.append(path) f.write(img2pdf.convert(imgs, layout_fun=layout_fun))
def from_photo_to_pdf(photo_path): startTime_pdf2img = datetime.datetime.now() # 开始时间 # 1、生成地址列表 photo_list = os.listdir(photo_path) photo_list = [os.path.join(photo_path, i) for i in photo_list] # 1、指定pdf的单页的宽和高 # A4纸张 # a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297)) # 我的自定义: a4inpt = (img2pdf.mm_to_pt(720), img2pdf.mm_to_pt(1080)) layout_fun = img2pdf.get_layout_fun(a4inpt) with open(photo_path + '\\1result.pdf', 'wb') as f: f.write(img2pdf.convert(photo_list, layout_fun=layout_fun)) endTime_pdf2img = datetime.datetime.now() # 结束时间 print('img2pdf 时间=', (endTime_pdf2img - startTime_pdf2img).seconds)
def __init__(self): self.input_files = None self.layout_fun_vertical = img2pdf.get_layout_fun( (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297))) self.layout_fun_horizontal = img2pdf.get_layout_fun( (img2pdf.mm_to_pt(297), img2pdf.mm_to_pt(210))) self.FILE_HANDLES = [] self.FINAL_LIST = set() self.INPUT_LIST = [] self.homedir = os.path.expanduser('~') # define temporary directory location if sys.platform == 'win32': self.tempdir = os.sep.join( [self.homedir, 'Application Data', 'pdfWorks']) else: self.tempdir = os.sep.join([self.homedir, '.pdfWorks'])
def compile_pdf_from_img(img_dir, output_pdf_filename): """ Compile and save .pdf from images :param img_dir: path to directory with images :param output_pdf_filename: full name (path + filename) of the output .pdf :return: None """ # Get list of images filenames imagelist = [ os.path.join(img_dir, f) for f in os.listdir(img_dir) if os.path.isfile(os.path.join(img_dir, f)) ] # Specify paper size (A4) a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297)) layout_fun = img2pdf.get_layout_fun(a4inpt) # Make and save .pdf with open(output_pdf_filename, "wb") as f: f.write(img2pdf.convert(imagelist, layout_fun=layout_fun)) return
def jpgToPdf(request): # img2pdf pip if request.method == "POST": # creating random folder name for each user res = ''.join(random.choice(string.ascii_lowercase) for x in range(10)) path_to_upload = os.path.join( './convertor/static/uploaded_files/jpg2pdf', str(res)) os.makedirs(path_to_upload) files = request.FILES files_list = [] for file in files.getlist('files'): files_list.append(file) a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297)) layout_fun = img2pdf.get_layout_fun(a4inpt) with open(path_to_upload + "/sample.pdf", "wb") as f: f.write(img2pdf.convert(files_list, layout_fun=layout_fun)) os.rename(path_to_upload + "/sample.pdf", path_to_upload + "/sample.txt") return render(request, 'jpgtopdf.html', {'url': str(res)}) return render(request, 'jpgtopdf.html')
def conv_image(file_name, args): """Convert an image to pdf.""" a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297)) if args == "A4": layout_fun = img2pdf.get_layout_fun(a4inpt) else: layout_fun = img2pdf.get_layout_fun() try: with open(file_name + ".pdf", "wb") as f: f.write(img2pdf.convert(file_name, layout_fun=layout_fun)) except ExifOrientationError as e: logger.warning("Error 1: {}".format(e)) piexif.remove(file_name) with open(file_name + ".pdf", "wb") as f: f.write(img2pdf.convert(file_name, layout_fun=layout_fun)) except (NegativeDimensionError, UnsupportedColorspaceError, ImageOpenError, JpegColorspaceError, PdfTooLargeError, AlphaChannelError, ExifOrientationError) as e: logger.warning("Error 2: {}".format(e)) raise return True
async def download(self): if not os.path.exists('downloads/'): os.mkdir('downloads/') if isinstance(self.title, dict): title = f"{self.title['japanese']}-{self.title['english']}" else: title = self.title manga: bsoup = await http.scrape(self.url) reader = manga.find_all('img', alt='image host') img = [img['src'] for img in reader] _bytes = [] print(f"Downloading {title}-chapter-{self.chapter} into PDF file...") for im, i in zip(img, range( 1, len(img) + 1)): # This HTTP requests is slow, help me to make it faster. req = await http.new('GET', im) if req.status_code == 200: _bytes.append(req.content) print(f"{i}. Image size: {format_size(len(req.content))}") a4inpt = (img2pdf.mm_to_pt(200), img2pdf.mm_to_pt(300)) layout_fun = img2pdf.get_layout_fun(a4inpt) date = datetime.now() path = f"downloads/{title}-chapter-{self.chapter}.pdf" with open(path, "wb") as f: f.write(img2pdf.convert(_bytes, layout_fun=layout_fun)) print(f"Download complete, path: {path}") return path
def render_to_pdf(save_path, file_name=None): """ Docstring """ print("Rendering to PDF...") a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297)) layout_fun = img2pdf.get_layout_fun(a4inpt) final_file_name = save_path if file_name: final_file_name = f"{final_file_name}/{file_name}" else: final_file_name = f"{final_file_name}/charts.pdf" with open(final_file_name, "wb") as f: f.write( img2pdf.convert([ i.path for i in os.scandir(save_path) if i.name.endswith(".jpg") ], dpi=150, layout_fun=layout_fun)) print("Succesfully rendered PDF...") return final_file_name
newfilepath = os.path.join(folder_path,img_names[i]) except Exception as e : print (e) break shutil.move(oldfilepath,newfilepath) folder_count += 1 img_names = [f for f in os.listdir(current_dir) if os.path.isfile(os.path.join(current_dir, f))] for current_dir in dirs: current_dir = os.path.join(ROOT_DIR, current_dir) current_dir = os.path.join(current_dir, 'collages') dir_names = [f for f in os.listdir(current_dir) if os.path.isdir(os.path.join(current_dir, f))] for folder in dir_names: folder_path = os.path.join(current_dir, folder) image_path = os.path.join(current_dir,'out_'+folder+'.jpg') args = {'folder':folder_path, 'width':850 , 'init_height':720, 'shuffle' : True , 'output' : image_path} collage_maker.prepare(args) # add margin ImageOps.expand(Image.open(image_path),border=60,fill='white').save(image_path) # convert to pdf a4inpt = (img2pdf.mm_to_pt(210),img2pdf.mm_to_pt(297)) # specify page size (A4) layout_fun = img2pdf.get_layout_fun(a4inpt) with open(os.path.join(current_dir,'out_'+folder+'.pdf'), "wb") as f: f.write(img2pdf.convert(image_path, layout_fun=layout_fun))
' pages and it will take a long time.') print('\n') i = 0 for url in listimg: i = i + 1 print('Downloading ' + str(i)) htmlimg = gethtml(url) #htmlimg = requests.get(url) with open(str(i) + ".jpg", "wb") as f: f.write(htmlimg.content) print(str(i) + ' finished') print('\n') time.sleep(1) listjpg = [] for j in range(i): listjpg.append(str(j + 1) + '.jpg') #print(listjpg) print('Please input the name of pdf:') name = input() a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297)) layout_fun = img2pdf.get_layout_fun(a4inpt) with open(str(name) + '.pdf', 'wb') as f: f.write(img2pdf.convert(listjpg, layout_fun=layout_fun)) for j in range(i): os.remove(str(j + 1) + '.jpg') print('Finish! Welcome to UtoSpace to explore more! www.utospace.club') time.sleep(5)
def export_pdf(request): if (request.method == 'POST'): # Get list of documents id documents_pdf = request.POST.get('documents_pdf') #get credit application ID credit_app_id = request.POST.get('credit_app_id') # fromm settings.py get media root path fileroot = settings.MEDIA_ROOT # Create full filepath filepath = '{}{}{}'.format(fileroot, '/', credit_app_id) #Split list of document ID's split_document_id = documents_pdf.split(',') #path to save PDF pdfpath = '{}{}{}{}{}{}'.format(fileroot, '/', credit_app_id, '/', credit_app_id, '.pdf') # Array to save full length path pdf_documents = [] # Array to save full length path pdf_documents = [] #Opened images image_bits = [] #file paths image_paths = [] #create dict with splitted values for value in range(len(split_document_id)): full_doc_name = '{}{}{}{}{}{}'.format(credit_app_id, '/', credit_app_id, '_', split_document_id[value], '.jpg') pdf_documents.append(full_doc_name) #open list of images for document in range(len(pdf_documents)): opened_img = Image.open('{}{}{}'.format(fileroot, '/', pdf_documents[document])) image_bits.append(opened_img) #close image opened_img.close() for value in range(len(image_bits)): image_paths.append(image_bits[value].filename) #specify paper size letter_size = (img2pdf.mm_to_pt(215.9), img2pdf.mm_to_pt(279.4)) #set paper size varibale to img2pdf layout_fun = img2pdf.get_layout_fun(letter_size) #convert images final_pdf = img2pdf.convert(image_paths, layout_fun=layout_fun) #Open or create pdf file file = open(pdfpath, 'wb') #write pdf files file.write(final_pdf) #close file file.close() return HttpResponse('success')
# Hardcoded recommended pixel sizes for target dpi's pixel_quality = { 'A6H': (1240, 1748), 'A6M': (620, 874), 'A6L': (310, 437), 'A5H': (1748, 2480), 'A5M': (874, 1240), 'A5L': (437, 620), 'A4H': (2480, 3508), 'A4M': (1240, 1754), 'A4L': (620, 877) } # Set the paper size, font size and image quality if paper_size == 'A6': paper_input = (img2pdf.mm_to_pt(105), img2pdf.mm_to_pt(148)) font_scaling = 2 # used later to adjust font size relative to page if quality == 'L': pixels = pixel_quality['A6L'] elif quality == 'M': pixels = pixel_quality['A6M'] else: pixels = pixel_quality['A6H'] elif paper_size == 'A5': paper_input = (img2pdf.mm_to_pt(148), img2pdf.mm_to_pt(210)) font_scaling = 1.5 if quality == 'L': pixels = pixel_quality['A5L'] elif quality == 'M': pixels = pixel_quality['A5M'] else:
def get_dimensions(image, din_format): from model.ImageManipulation import ImageManipulation width, height = ImageManipulation.get_size_indices(image) return img2pdf.mm_to_pt(DIN_FORMAT[din_format][width]), img2pdf.mm_to_pt( DIN_FORMAT[din_format][height])