2014-07-26 10 views
5

Desidero visualizzare il percorso completo del file pdf insieme al suo contenuto visualizzato sul browser. Il mio script ha un input html, in cui l'utente inserirà il nome del file e invierà il modulo. Lo script cercherà il file, se trovato nelle sottodirectory produrrà il contenuto del file nel browser e visualizzerà anche il suo nome. Sono in grado di visualizzare il contenuto ma non riesco a visualizzare contemporaneamente il nome completo completo O se visualizzo il nome del file ottengo la visualizzazione dei caratteri illeggibili per i contenuti. Per favore guida.come visualizzare il contenuto del file pdf e il suo nome completo nel browser usando lo script cgi python?

enter link description here

sceneggiatura a.py:

import os 
import cgi 
import cgitb 
cgitb.enable() 
import sys 
import webbrowser 

def check_file_extension(display_file): 
    input_file = display_file 
    nm,file_extension = os.path.splitext(display_file) 
    return file_extension 

form = cgi.FieldStorage() 

type_of_file ='' 
file_nm = '' 
nm ='' 
not_found = 3 

if form.has_key("file1"): 
    file_nm = form["file1"].value 

type_of_file = check_file_extension(file_nm) 

pdf_paths = [ '/home/nancy/Documents/',] 

# Change the path while executing on the server , else it will throw error 500 
image_paths = [ '/home/nancy/Documents/'] 


if type_of_file == '.pdf': 
    search_paths = pdf_paths 
else: 
    # .jpg 
    search_paths = image_paths 
for path in search_paths: 
    for root, dirnames, filenames in os.walk(path): 
     for f in filenames: 
      if f == str(file_nm).strip(): 
       absolute_path_of_file = os.path.join(root,f) 
       # print 'Content-type: text/html\n\n' 
       # print '<html><head></head><body>' 
       # print absolute_path_of_file 
       # print '</body></html>' 
#     print """Content-type: text/html\n\n 
# <html><head>absolute_path_of_file</head><body> 
# <img src=file_display.py /> 
# </body></html>""" 
       not_found = 2 
       if search_paths == pdf_paths: 
        print 'Content-type: application/pdf\n' 
       else: 
        print 'Content-type: image/jpg\n' 
       file_read = file(absolute_path_of_file,'rb').read() 
       print file_read 
       print 'Content-type: text/html\n\n' 
       print absolute_path_of_file 
       break 
     break 
    break 

if not_found == 3: 
    print 'Content-type: text/html\n' 
    print '%s not found' % absolute_path_of_file 

L'HTML è un html regolare con il campo solo 1 ingresso per il nome del file.

risposta

4

Non è possibile. Almeno non così semplice. Alcuni browser Web non visualizzano PDF, ma chiedono all'utente di scaricare il file, alcuni visualizzano essi stessi, alcuni incorporano un componente di visualizzazione PDF esterno, altri avviano un visualizzatore PDF esterno. Non esiste un modo standard, cross browser per incorporare il PDF in HTML, che sarebbe necessario se si desidera visualizzare il testo arbitrario e il contenuto PDF.

Una soluzione di fallback, che funziona su ogni browser, renderebbe le pagine PDF sul server come immagini e le offrirà al cliente. Ciò mette un po 'di stress sul server (processore, memoria/disco per il caching, larghezza di banda).

Alcuni browser moderni compatibili con HTML5 possono eseguire il rendering di PDF con Mozilla's pdf.js su un elemento canvas.

Per gli altri è possibile provare a utilizzare <embed>/<object> per utilizzare il plug-in di Adobe come described on Adobe's The PDF Developer Junkie Blog.


rendering delle pagine sul server

Rendering e servire le pagine PDF come immagini ha bisogno di alcuni software sul server per interrogare il numero di pagine e per estrarre e rendere una determinata pagina come immagine.

Il numero di pagine può essere determinato con il programma pdfinfo da Xpdf oi libpoppler utilità riga di comando. La conversione di una pagina dal file PDF in un'immagine JPG può essere eseguita con convert dagli strumenti ImageMagick. Un programma molto semplice CGI utilizzando questi programmi:

#!/usr/bin/env python 
import cgi 
import cgitb; cgitb.enable() 
import os 
from itertools import imap 
from subprocess import check_output 

PDFINFO = '/usr/bin/pdfinfo' 
CONVERT = '/usr/bin/convert' 
DOC_ROOT = '/home/bj/Documents' 

BASE_TEMPLATE = (
    'Content-type: text/html\n\n' 
    '<html><head><title>{title}</title></head><body>{body}</body></html>' 
) 
PDF_PAGE_TEMPLATE = (
    '<h1>{filename}</h1>' 
    '<p>{prev_link} {page}/{page_count} {next_link}</p>' 
    '<p><img src="{image_url}" style="border: solid thin gray;"></p>' 
) 

SCRIPT_NAME = os.environ['SCRIPT_NAME'] 


def create_page_url(filename, page_number, type_): 
    return '{0}?file={1}&page={2}&type={3}'.format(
     cgi.escape(SCRIPT_NAME, True), 
     cgi.escape(filename, True), 
     page_number, 
     type_ 
    ) 


def create_page_link(text, filename, page_number): 
    text = cgi.escape(text) 
    if page_number is None: 
     return '<span style="color: gray;">{0}</span>'.format(text) 
    else: 
     return '<a href="{0}">{1}</a>'.format(
      create_page_url(filename, page_number, 'html'), text 
     ) 


def get_page_count(filename): 

    def parse_line(line): 
     key, _, value = line.partition(':') 
     return key, value.strip() 

    info = dict(
     imap(parse_line, check_output([PDFINFO, filename]).splitlines()) 
    ) 
    return int(info['Pages']) 


def get_page(filename, page_index): 
    return check_output(
     [ 
      CONVERT, 
      '-density', '96', 
      '{0}[{1}]'.format(filename, page_index), 
      'jpg:-' 
     ] 
    ) 


def send_error(message): 
    print BASE_TEMPLATE.format(
     title='Error', body='<h1>Error</h1>{0}'.format(message) 
    ) 


def send_page_html(_pdf_path, filename, page_number, page_count): 
    body = PDF_PAGE_TEMPLATE.format(
     filename=cgi.escape(filename), 
     page=page_number, 
     page_count=page_count, 
     image_url=create_page_url(filename, page_number, 'jpg'), 
     prev_link=create_page_link(
      '<<', filename, page_number - 1 if page_number > 1 else None 
     ), 
     next_link=create_page_link(
      '>>', 
      filename, 
      page_number + 1 if page_number < page_count else None 
     ) 
    ) 
    print BASE_TEMPLATE.format(title='PDF', body=body) 


def send_page_image(pdf_path, _filename, page_number, _page_count): 
    image_data = get_page(pdf_path, page_number - 1) 
    print 'Content-type: image/jpg' 
    print 'Content-Length:', len(image_data) 
    print 
    print image_data 


TYPE2SEND_FUNCTION = { 
    'html': send_page_html, 
    'jpg': send_page_image, 
} 


def main(): 
    form = cgi.FieldStorage() 
    filename = form.getfirst('file') 
    page_number = int(form.getfirst('page', 1)) 
    type_ = form.getfirst('type', 'html') 

    pdf_path = os.path.abspath(os.path.join(DOC_ROOT, filename)) 
    if os.path.exists(pdf_path) and pdf_path.startswith(DOC_ROOT): 
     page_count = get_page_count(pdf_path) 
     page_number = min(max(1, page_number), page_count) 
     TYPE2SEND_FUNCTION[type_](pdf_path, filename, page_number, page_count) 
    else: 
     send_error(
      '<p>PDF file <em>{0!r}</em> not found.</p>'.format(
       cgi.escape(filename) 
      ) 
     ) 


main() 

C'è Python per libpoppler, quindi la chiamata al programma esterno pdfinfo potrebbe essere sostituito facilmente con quel modulo. Può anche essere usato per estrarre più informazioni per le pagine come i collegamenti nelle pagine PDF per creare mappe di immagini HTML per loro. Con il libcairo collegamenti Python può essere anche possibile eseguire il rendering di una pagina senza un processo esterno.

+0

Potete suggerire una soluzione alternativa dove questo può essere raggiunto? – user956424

+0

@ user956424 Ho aggiunto alcune soluzioni alla risposta. – BlackJack

+0

http://stackoverflow.com/users/3815611/blackjack Voglio ottenere questo risultato utilizzando cgi, python alone..no js – user956424

Problemi correlati