• Artigos
  • Projetos
  • Download
  • Docs
  • Enviar Artigo
  • ?

PDF 2 IMG

21/12/2009    Ler e Comentar






É uma pequena classe que se utiliza de API's exteriores para conversão
de Pdf em Imagem e assim podemos mostrá-las.
Em faze inicial de construção ainda apresenta somente
funções básicas como Avançar, Retroceder, ZoomIn, ZoomOut.
Mais facilmente podem-se programar outras funções até o sonhado PRINT.


PHP peca quanto temos de transformar o temos em digital para uma folha de papel comum.
Lendo muitos tópicos vemos o esforço de todos para dar uma "burladinha" nisso
se utilizando de aplicativos como Web-Browsers ou Adobe Reader,Foxit e afins...
Mais se nosso relatório em pdf que ta prontinho, e em vez de abri-lo em um aplicativo.
Exterior oque acaba se tornando deselegante pudesse ser
Aberto em nosso próprio aplicativo?
Não seria uma maravilha!

Dll pode ser obtida em :
http://www.mandamais.com.br/download/e4kx21122009111830
OBS:up próprio

Ghost Script Pode ser obtido em:
http://ufpr.dl.sourceforge.net/project/ghostscript/GPL%20Ghostscript/8.70/gs870w32.exe

ImageMagick pode ser obtid em:
http://www.imagemagick.org/download/binaries/ImageMagick-6.5.8-7-Q16-windows-dll.exe



//###############         Pdf2Img.php
<?php
class Pdf2Img{
    
    
    public function 
LePdf($File,$Pag,$Res,$Qual){
        
//observar que a pagina 0 corresponde a 1º pagina
        
$PagPdf = "[".$Pag."]";
        
$this->Im = new Imagick();
        
$this->Im->setResolution($Res,$Res);
        
$this->Im->readImage("$File"."$PagPdf");
        
$this->Im->setCompressionQuality($Qual);
        
    }
    public function 
PorcentImg($Porc){
        
//cauculo no maximo 50 porcento da imagem original para não pesar demais o processo de conversão
        
$ImgPercento[0]= 1;
        
$ImgPercento[10]= 5; 
        
$ImgPercento[20]= 10;
        
$ImgPercento[30]= 15;
        
$ImgPercento[40]= 20;
        
$ImgPercento[50]= 25;
        
$ImgPercento[60]= 30; 
        
$ImgPercento[70]= 35;
        
$ImgPercento[80]= 40;
        
$ImgPercento[90]= 45;
        
$ImgPercento[100]= 50; 
    
    
        
$H = $this->Im->getImageHeight();
        
$H = $H * ($ImgPercento[$Porc]/100);
        
$W = $this->Im->getImageWidth();
        
$W = $W * ($ImgPercento[$Porc]/100);
        
//dimensiona a imagem com base no tamanho da pagina do pdf divido pela porcentagem requisitada
        //aplica o filter lanczos com 1 e embassamento para diminuir possiveis arestas,as vezes nao se faz necessario
        
$this->Im->resizeImage($W,$H,imagick::FILTER_LANCZOS,1); 
        
    }
    public function 
GravaArquivo($NomeArq){
    
        
$this->Im->writeImage("$NomeArq");
        
$this->Im->clear();
        
$this->Im->destroy();
        
    }
}
?>

//###############         preview.php
<?php


/************** Todos os Requerimentos ************

-      Ghostscript 
-      ImageMagick
-      php_imagick.dll
-     Microsoft Visual C++ 2008 Redistributable

************** Versões utilizadas ******************

-      Ghostscript  8.70
-     ImageMagick -6.5.8-6-Q16-windows-dll.exe
-    php_imagick.-6.5.8-6-Q16-windows-dll renomeada para php_imagick.dll

**************Instruções******************

-      instalar o Ghostscript  8.70 normal como qualquer outro programa
-      instalar o ImageMagick normal como qualquer outro programa
-     instalar o Microsoft Visual C++ 2008 Redistributable normalmente
-      colocar a dll - php_imagick.dll dentro do diretorio ext do seu php gtk e colocar seu nome no php.ini

**************Notas******************
-      Ghostscript  8.70  trabalha efetivamente com a conversao do pdf
-     ImageMagick trabalha com a conversao e definicoes da imagem
-    Microsoft Visual C++ 2008 Redistributable - nao sei informar heheheh mais e necessário
-    php_imagick.dll  faz a ligacao do php com imageMagick ja que infeslimente php naum tem suporte nativo a essa explendorosa extensao.

************** Objetivo ************

Imprementar Processo de Impressão - direto
Tirar a utlização de aplicativos exterioes a nossa aplicação

**************Anotações************

Processador Semprom 1.57
Tempo Medio De Converção : 3 - 8 Segundos Variados Pelo Zoom e Tamanho da Imagem Requitada
------------------------------------------------------------------------------------------------------------------------------

**************Versão 1.0 aberta a testes************

Autor : Fernando Scaranello
Imail : curso_c.c@hotmail.com
Ciências da Computação 3º P.
Data:        18/12/2009
Hora:        19:04

OBS: Qualquer alteração ou impletação de novas Funçoes, se possivel mandar o Source para mim. ;)

*/

//Pdf2Img.php Classe Responsavel pela Conversão do Pdf Em Imagem
//Utilizada a versão Jpeg pelo Seu tamanho reduzido
//Obs:Foi utlizada extensao Bmp a fim de testes ,e a imagem ficou com 24MB em resolucao 300x300

require_once 'Pdf2Img.php';


Class 
PdfPreview{
    
    protected 
$PagNum = -1;
    protected 
$PagTot;
    protected 
$Zoom;
    
    function 
__construct($TotPag,$ZoomInicial){
        
        
$this->Pdf2Img = new Pdf2Img;//instancia a classe Pdf2Img
        
$this->PagTot = $TotPag; //define o numero total de pagina conforme passado no construtor
        
$this->Zoom = $ZoomInicial; //define o zoom inical conforme passado no construtor
        
$this->Btns();
        
$this->Entrys();
        
$this->PainelSts();
        
$this->Img();
        
$this->layout();
        
$this->Wnd();
        
    }
    protected function 
Btns(){
        
        
$icone[0] = GtkImage::new_from_stock(Gtk::STOCK_GO_BACK,Gtk::ICON_SIZE_BUTTON);
        
$icone[1] = GtkImage::new_from_stock(Gtk::STOCK_GO_FORWARD,Gtk::ICON_SIZE_BUTTON);
        
$icone[2] = GtkImage::new_from_stock(Gtk::STOCK_ZOOM_IN,Gtk::ICON_SIZE_BUTTON);
        
$icone[3] = GtkImage::new_from_stock(Gtk::STOCK_ZOOM_OUT,Gtk::ICON_SIZE_BUTTON);
    
        
$this->botao["ant"] = new GtkButton;
        
$this->botao["ant"]->set_image($icone[0]);
        
$this->botao["prox"] = new GtkButton;
        
$this->botao["prox"]->set_image($icone[1]);
        
        
$this->botao["MaisZoon"] = new GtkButton;
        
$this->botao["MaisZoon"]->set_image($icone[2]);
        
        
$this->botao["MenosZoon"] = new GtkButton;
        
$this->botao["MenosZoon"]->set_image($icone[3]);
        
        
//todos o handles de conexao
        
$this->AntId = $this->botao["ant"]->connect_simple('clicked',array($this,'PagAnt'));
        
$this->ProxId = $this->botao["prox"]->connect_simple('clicked',array($this,'PagProx'));
        
$this->ZIId = $this->botao["MaisZoon"]->connect_simple('clicked',array($this,'ZoomIn'));
        
$this->ZOId = $this->botao["MenosZoon"]->connect_simple('clicked',array($this,'ZoomOut'));
    
    }
    public function 
BlockAll(){
    
        
$this->botao["ant"]->block($this->AntId);
        
$this->botao["prox"]->block($this->ProxId);
        
$this->botao["MaisZoon"]->block($this->ZIId);
        
$this->botao["MenosZoon"]->block($this->ZOId);
        
    }
    public function 
UnBlockAll(){
    
        
$this->botao["ant"]->unblock($this->AntId);
        
$this->botao["prox"]->unblock($this->ProxId);
        
$this->botao["MaisZoon"]->unblock($this->ZIId);
        
$this->botao["MenosZoon"]->unblock($this->ZOId);
        
    }
    public function 
PagAnt(){
    
        if( 
$this->PagNum > 0 ){
            
            
$this->PagNum -=1;
            
$this->PainelSts();
            
$this->BlockAll();
            
$this->LoadImg($this->PagNum,$this->Zoom);
            
$this->MudaImg();
            
$this->UnBlockAll();
            
        }
        
    }
    public function 
PagProx(){
    
        if(  
$this->PagNum  <= ($this->PagTot-2) ){
            
            
$this->PagNum +=1;
            
$this->PainelSts();
            
$this->BlockAll();
            
$this->LoadImg($this->PagNum,$this->Zoom);
            
$this->MudaImg();
            
$this->UnBlockAll();
            
        }
        
    }
    public function 
ZoomIn(){
    
        if( (( 
$this->Zoom >=0 )&&($this->Zoom<100)) && ($this->PagNum >= 0) ){
            
            
$this->Zoom +=10;
            
$this->PainelSts();
            
$this->BlockAll();
            
$this->LoadImg($this->PagNum,$this->Zoom);
            
$this->MudaImg();
            
$this->UnBlockAll();
            
        }
        
    }
    public function 
ZoomOut(){
    
        if( ( 
$this->Zoom > 1 )&&($this->Zoom<=100) && ($this->PagNum >= 0) ){
            
            
$this->Zoom -=10;
            
$this->PainelSts();
            
$this->BlockAll();
            
$this->LoadImg($this->PagNum,$this->Zoom);
            
$this->MudaImg();
            
$this->UnBlockAll();
            
        }
        
    }
    public function 
LoadImg($Pag,$Zoom){
        
//test.pdf o arquivo utlizado no relatorio para testes
        //$pag o numero da pagina requisitada
        //200 a resolucao
        //100 qualidade maxima
        //Obs : Qualidades inferios não reduziram siguinificamento o tempo , mais diminui dastricamente a qualidade da imagem gerada
        
$this->Pdf2Img->LePdf("test.pdf",$Pag,200,100);
        
$this->Pdf2Img->PorcentImg($Zoom);
        
$this->Pdf2Img->GravaArquivo("prev.jpg");//grava a imagem com o nome e extensao selecionado
        
$this->MudaImg();
        
    }
    public function 
MudaImg(){
        
//remove a imagem atual e implanta a nova imagem
        
$this->frame_image->remove($this->frame_image->get_child());
        
$this->NewImg = GtkImage::new_from_file('prev.jpg');//troca pela imagem gerada
        
$this->frame_image->add($this->NewImg);
        
$this->frame_image->show_all();
    
    }
    
//todos os entrys utlizados
    //no caso so 1 - hehe
    
protected function Entrys(){
    
        
$this->entry["PagNumZoom"] = new GtkEntry;
        
$this->entry["PagNumZoom"]->set_alignment(0.5);//Alinhamento Exatamente ao centro
        
$this->entry["PagNumZoom"]->set_size_request(150,30);
        
$this->entry["PagNumZoom"]->set_sensitive(false);//não pode ser selecionado
        //Cor de fundo
        
$this->entry["PagNumZoom"]->modify_base(Gtk::STATE_INSENSITIVE, GdkColor::parse('#e5f2e5'));
        
//Cor da Letra
        
$this->entry["PagNumZoom"]->modify_text(Gtk::STATE_INSENSITIVE, GdkColor::parse('#000000'));
    
    
    }
    protected function 
PainelSts(){
        if(
$this->Zoom == 0){
            
            
$Z = "Min";
            
        }
        elseif(
$this->Zoom == 100){
            
            
$Z = "Max";
        
        }
        else{
                        
            
$Z = $this->Zoom ."%";
        
        }
        
$PagN = $this->PagNum+1;
        
$this->entry["PagNumZoom"]->set_text("$PagN de $this->PagTot -"." $Z");
        
    }
    Protected function 
Img(){
        
//imagem intro de minha aplicação
        //encontrada dentro da pasta - obviamente
        
        
$this->NewImg = GtkImage::new_from_file('intro.jpg');
        
$this->frame_image = new GtkFrame;
        
$this->frame_image->add($this->NewImg);
    
        
$this->entry["PagNumZoom"]->set_text("Avance P/ Começar");
        
$this->Scroll = new GtkScrolledWindow();
        
$this->Scroll->set_policy(Gtk::POLICY_AUTOMATIC,Gtk::POLICY_AUTOMATIC);
        
$this->Scroll->set_size_request(700,500);
        
$this->Scroll->set_shadow_type(0);
        
$this->Scroll->add_with_viewport($this->frame_image);
    
    }
    protected function 
layout(){
        
//posiciona todos os aplicativos na sua posição
        //utlizando um fixed - mais conveniente para mim 
        
        
$this->FixFunc = new GtkFixed();
        
$this->FixFunc->put($this->botao["ant"],0,0);
        
$this->FixFunc->put($this->botao["prox"],32,0);
        
$this->FixFunc->put($this->botao["MenosZoon"],64,0);
        
$this->FixFunc->put($this->botao["MaisZoon"],96,0);
        
$this->FixFunc->put($this->entry["PagNumZoom"],130,0);
            
        
$this->Posix = new GtkFixed();
        
$this->Posix->put($this->Scroll,50,50);
        
$this->Posix->put($this->FixFunc,50,555);
    }
    Protected function 
Wnd(){
    
// CRIA A JANELA
        
$this->Janela = new GtkWindow();
        
$this->Janela->set_size_request(800,600);
        
$this->Janela->set_keep_below(true);
        
$this->Janela->set_resizable(false);//define se a janela pode ser redimensionada
        
$this->Janela->set_title('Preview Relatórios'); //define o titulo da janela
        
$this->Janela->connect_simple('destroy',array('Gtk', 'main_quit'));
        
$this->Janela->add($this->Posix);
        
$this->Janela->show_all();
        
    }
}
//(Numero da Pagina,Zoom Inicial)
//numero total de pagina
//nao achei uma funcao que fizesse isso altomaticamente então foi improvizado
//40 de zoom inicial - geralmente cabe dentro do scrool
new PdfPreview(40,40);
Gtk::main();

?>




Comentários

 Adicionar Comentário
 login
 Senha
 Título
 Comentário

Livros




    Outros

    Busque conteúdo no site
    Participe de nosso grupo no google

    [Grupo]  [Arquivos] [Mapa Usuários]

    Google

    Parceiros

 
Designed by Wolfgang Bartelme Designed by Wolfgang Bartelme

© 2006 Wordpress Themes | Theme (Not so) Fresh
XHTML CSS RSS