Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Wagner Martins - SC

Gerar pdf mais de uma vez

Recommended Posts

Tenho um script que gera um arquivo pdf de um formulário AR dos Correios, ele só censegue gerar se for gerada apenas um formulario, como faço para que eu consiga fazer mais de um formulário para colocar por exemplo dois formulario no mesmo arquivo pdf?

 

<? 
function bulk_admin_AR_footer() {


global $post_type;






if ( 'shop_order' == $post_type ) {


?>


<script type="text/javascript">


jQuery(function() {


jQuery('<option>').val('gerar_ar').text('<?php _e( 'Gerar AR', 'woocommerce' )?>').appendTo("select[name='action']");


jQuery('<option>').val('gerar_ar').text('<?php _e( 'Gerar AR', 'woocommerce' )?>').appendTo("select[name='action2']");


});


</script>


<?php


}


}






/**


* Process the new bulk actions for changing order status


*/


function bulk_action_AR() {






$wp_list_table = _get_list_table( 'WP_Posts_List_Table' );


$action = $wp_list_table->current_action();






// Bail out if this is not a status-changing action


if ( strpos( $action, 'gerar_' ) === false ) {


return;


}






$new_status    = substr( $action, 5 ); // get the status name from action


$report_action = 'gerada' . $new_status;






$changed = 0;






$post_ids = array_map( 'absint', (array) $_REQUEST['post'] );






$sendback = add_query_arg( array( 'post_type' => 'shop_order', $report_action => true, 'changed' => $changed, 'ids' => join( ',', $post_ids ) ), '' );


wp_redirect( $sendback ); // esse é o padrão






exit();


}














function bulk_action_AR_notices() {


global $post_type, $pagenow;






// Bail out if not on shop order list page


if ( 'edit.php' !== $pagenow || 'shop_order' !== $post_type ) {


return;


}


if ( isset( $_REQUEST[ 'gerada_ar' ] ) ) {






$number = isset( $_REQUEST['changed'] ) ? absint( $_REQUEST['changed'] ) : 0;


$message = 'AR geradas em uma nova aba. Se não abrir, <a href="'. get_admin_url() .'admin-ajax.php/?action=get_AR_pdf&ids='.$_GET['ids'].'" target="_blank">clique aqui</a>.';


echo '<div class="updated"><p>' . $message . '</p></div>';


}


}










function get_AR_pdf(){






/**


 *


 * WooCommerce


 *


 * Biblioteca para PDF


 *


 */


require_once("dompdf/dompdf_config.inc.php");








$html .= ' <html>';


$html .= ' <head>';


$html .= '  <title>AR Correios</title>';


$html .= ' <style type="text/css">


@media print {
    .panel-default > .panel-heading {
      background-color: #F5F5F5 !important;
    }    
}


@page :first{margin:1cm;}
@page,@page :left,@page :right{margin:.5cm;}


body{line-height:1.15;font-size:85%;}
ul,ol{margin:0;padding:0;}
label,input,button,select,textarea{line-height:12px;}
table{width:100%;}
table td{padding-bottom:5px;}
label{font-weight:700;margin:0;}
span{line-height:13px;}
.panel-heading{font-weight:700;padding:8px;}
.panel-body{padding:8px;}
.box{border:0 solid gray;margin-bottom:.3cm;padding:3px;}
.box-recortar{border:1px dotted #969696;margin:.3cm 0;}
.table-condensed th,.table-condensed td{padding:5px 0!important;}
.table th,.table td{border-top:1px solid gray;line-height:13px;text-align:left;vertical-align:top;padding:5px 0!important;}
.checklist li{line-height:15px;display:inline;list-style-type:circle;list-style-position:outside;padding:15px;}
.pedido .cabecalho{margin-bottom:1.5cm;}
.table-date{width:90px!important;}
.table-datehour{width:140px!important;}
.table-user{width:160px!important;}
.table-wativo{width:45px!important;}
.table-id{width:60px!important;text-align:center!important;}
.table-periodo{width:120px!important;text-align:center!important;}
.table-strong{font-weight:700;}
.produtos-pedido .variacao{color:#969696;line-height:13px;}
.produtos-pedido .sku{color:#969696;line-height:13px;font-size:10px;}


.clear{clear:both;}
.left{float:left;}
.right{float:right;}


.etiquetas-correios2 .etiqueta{width:15cm;}
.etiquetas-correios4 .etiqueta{margin-right:1cm;width:8.5cm;margin-bottom:2cm;}
.etiquetas-correios4 li,.etiquetas-simples li{width:50%;display:inline-block;}


.etiqueta label{margin-bottom:5px;}
.etiqueta .cep-barras{margin:7px 0;}
.etiqueta .info{font-size:50%!important;color:gray;}
.etiqueta-pedido .col-remetente{width:35%;}
.etiqueta-pedido .col-destinatario{width:65%;}
.etiqueta-pedido .col-chancela{float:left;width:35%;}
.etiqueta-pedido .destinatario{float:left;width:65%;}
.etiqueta-pedido .chancela{border:1px solid #000;}


.text-center,.table-center{text-align:center!important;}
.text-right,.table-right{text-align:right!important;}
.pedido .data-hora,.produtos-pedido .info span{display:block;font-size:10px;}
table .titulo-total,table .valor{text-align:right;}
.table-valor,.table-valor-traco,.table-inteiro,.table-moeda{width:70px!important;text-align:right!important;}


.table-center { text-align: center !important; }
.table-date { width: 90px !important; }
.table-datehour { width: 140px !important; }
.table-user { width: 160px !important; }
.table-wativo { width: 45px !important; }
.table-id { width: 60px !important; text-align: center !important; }
.table-valor { width: 70px !important; text-align: right !important; }
.table-valor-traco { width: 70px !important; text-align: right !important; }
.table-inteiro { width: 70px !important; text-align: right !important; }
.table-moeda { width: 70px !important; text-align: right !important; }
.table-periodo { width: 120px !important; text-align: center !important; }
.table-right { text-align: right !important; }
.table-strong { font-weight: bold; }


.produtos-pedido .variacao { color: #969696; line-height: 13px; }
.produtos-pedido .info span {display: block; font-size: 10px; }
.produtos-pedido .sku { color: #969696; line-height: 13px; font-size: 10px; }


.produtos-pedido .col-foto { width: 70px; }
.produtos-pedido .col-qtd { width: 90px; }
.produtos-pedido .col-qtd input { width: 32px;  }
.pagina-carrinho .col-qtd .qtd * { display: inline-block; vertical-align: middle; text-align: center !important; }
.produtos-pedido .col-valor-unitario { width: 130px; }
.produtos-pedido .col-valor-total { width: 130px; font-weight: bold; }


.colunas-1{width:100%;}
.colunas-2{width:50%;}
.colunas-3{width:33.3%;}
.colunas-4{width:25%;}
.colunas-5{width:20%;}
.colunas-6{width:16.6%;}
.colunas-7{width:14.2px;}


.fonte-mini{font-size: 70% !important;line-height:1.1;}


.fonte-10{font-size:10px;line-height:12px;}
.fonte-11{font-size:11px;line-height:13px;}
.fonte-12{font-size:12px;line-height:14px;}
.fonte-13{font-size:13px;line-height:15px;}
.fonte-14{font-size:14px;line-height:16px;}
.fonte-15{font-size:15px;line-height:17px;}
.fonte-16{font-size:16px;line-height:18px;}
.fonte-17{font-size:17px;line-height:19px;}
.fonte-18{font-size:18px;line-height:20px;}


/* AVISO DE RECEBIMENTO //////////////////////////////////////////////////////////////////////////*/


.ar td {
    font-family: arial; 
    font-size: 8px;    
    vertical-align:top;    
    padding-bottom: 0px;
}


.ar .BordaInfDir{
        border-right: 2px solid black;
        border-bottom: 2PX solid black;
}
.ar .BordaInf{
        border-bottom: 2PX solid black;
}
.ar .BordaEsq{
        border-left: 2PX solid black;
}
.ar .BordaInfEsq{
        border-bottom: 2PX solid black;
        border-left: 2px solid black;
}
.ar .BordaSupEsr{
        border-bottom: 2PX solid black;
}
.ar .BordaDirTracejada{
        border-right: 1px dotted;
        text-align:center;
        vertical-align:middle;
}


.ar .BordaTodas{
        border-right: 2px solid black;
        border-left: 2PX solid black;
        border-top: 2px solid black;
        border-bottom: 2PX solid black;
}


.ar .style57 {font-size: 7px}
.ar .style58 {font-size: 1px}
.ar .style59 {
    font-size: 11px;
    font-style: italic;
    font-weight: bold;
}
.ar .style60 {
    font-size: 23px;
    font-weight: bold;
}
.ar .style62 {
    font-size: 12px;
    font-weight: bold;
}
</style>';


$html .= ' </head>';


$html .= ' <body>';


$html .= ' <page>';






$orders = $_GET['ids'];


$orders = explode(",", $orders);






$i=0; $a=0;


foreach ($orders as $key => $value) {






$pedido = $value;


$order = new WC_Order( $pedido );


$order = wc_get_order( $value );






//altura


$height = 150;


$top = ($height + 5) * $a;






//esquerda//direita


if($i%2){ $alinha = "right"; $a++; }else{ $alinha = "left";  }






$nome  = $order->shipping_first_name;


$sobrenome  = $order->shipping_last_name;


$endereco  = $order->shipping_address_1;


$endereco2  = $order->shipping_address_2;


$cidade  = $order->shipping_city;


$uf  = $order->shipping_state;


$cep  = $order->shipping_postcode;






$rates = $order->get_shipping_methods();


foreach ( $rates as $key => $rate ) {


        $tipoEnvio = $rate['method_id'];


            break;


}






$html .= '        <div class="ar ar-pedido page-break">
            
            <table width="689" height="367" border="0"  cellspacing="0" class="BordaTodas" style="width: 552px; height: 371px;">
            <tr>
                <td width="31" rowspan="12" valign="bottom" class="BordaDirTracejada">
                    <div align="center"><img src="http://www2.correios.com.br/enderecador/img/ar2_r3_c2.gif"></div>
                </td>
                <td width="7" height="30"> 
                </td>
                <td width="124" class="BordaInf">';
$html .= '<img src=http://www.digitalshark.com.br/hdmi/wp-content/plugins/AR-WooCommerce-Correios-master/imagem.php />';


$html .='</td>
                <td width="86" class="style58 BordaInf"><span class="style59">AVISO DE <br> RECEBIMENTO</span></td>
                <td colspan="3" align="center" valign="middle" class="BordaInf style60">AR</td>
                <td align="center" valign="middle" class="BordaInf style62"> </td>
                <td width="126" class="BordaInfEsq">DATA DE POSTAGEM </td>
            </tr>
            <tr>
                <td height="32"> </td>
                <td colspan="6" rowspan="2" class="BordaInfEsq">
                
                <table border="0" width="370px" height="176px" >
                    <tr>
                        <td valign="top" class="style24">
                            <span class="style36">DESTINATÁRIO</span><br>
                            <span class="style38">
 ';


 $html .=                            $nome. ' '.$sobrenome.'<br>'.$endereco .' '. $endereco2 .'<br>'.$cidade . ' '. $uf.'<br>'.$cep .'Pedido: {pedido_codigo}






                             </span>
                        </td>
                    </tr>
                    <tr>
                        <td align="center" valign="bottom">';


$html .= "<img src=http://www.digitalshark.com.br/hdmi/wp-content/plugins/AR-WooCommerce-Correios-master/post.php?cep=$cep />";




$html .='












</td>
                    </tr>
                    <tr>
                        <td align="left" valign="bottom">
                            <span class="style42">ENDEREÇO PARA DEVOLUÇÃO DO AR </span><br>
                            <span class="style43">
                            Rua Mendes Nunes 345 <br>Vila Campestre São Paulo - SP<br>04330-110<br>
                            </span> 
                        </td>
                    </tr>
                </table> 
             
             </td>
             <td class="BordaInfEsq">UNIDADE DE POSTAGEM</td>
         </tr>
         <tr>
             <td height="148"> </td>
             <td align="center" class="BordaInfEsq">CARIMBO<br>UNIDADE DE ENTREGA </td>
         </tr>
         <tr>
             <td height="32"> </td>
             <td colspan="2" align="center" class="BordaEsq"><strong>TENTATIVAS DE ENTREGA </strong></td>
             <td colspan="5" class="BordaInfEsq">DECLARAÇÃO DE CONTEÚDO (SUJEITO À VERIFICAÇÃO) 
             <br><span class="style57"></span></td>
         </tr>
         <tr>
             <td height="71" rowspan="6"> </td>
             <td rowspan="5" class="BordaEsq">1ª ________/________/________<br>
             <br>
             2ª ________/________/________<br>
             <br>
             3ª ________/________/________ </td>
             <td rowspan="5" align="center">______ : ______h<br>
             <br>
             ______ : ______h<br>
             <br>
             ______ : ______ h </td>
             <td height="9" colspan="4" align="center" valign="top" class="style57 BordaEsq"><strong>MOTIVO DE DEVOLUÇÃO </strong></td>
             <td rowspan="6" class="BordaInfEsq">RUBRICA E MATRÍCULA DO<br>
               CARTEIRO </td>
           </tr>
           <tr>
             <td width="21" height="58" rowspan="5" class="BordaInfEsq"><img src="http://www2.correios.com.br/enderecador/img/ar2_r6_c10.gif" alt=""></td>
             <td width="71" height="13"><span class="style57">Mudou-se</span></td>
             <td width="15" rowspan="5" class="BordaInf"><img src="http://www2.correios.com.br/enderecador/img/ar2_r5_c5.gif" alt=""></td>
             <td width="49"><span class="style57">Recusado</span></td>
           </tr>
           <tr>
             <td height="12"><span class="style57">Endereço insuficiente </span></td>
             <td width="49"><span class="style57">Não procurado </span></td>
           </tr>
           <tr>
             <td height="11"><span class="style57">Não existe o número </span></td>
             <td width="49"><span class="style57">Ausente</span></td>
           </tr>
           <tr>
             <td height="9" valign="middle"><span class="style57">Desconhecido</span></td>
             <td width="49" valign="middle"><span class="style57">Falecido</span></td>
           </tr>
           <tr>
             <td colspan="2" class="BordaInfEsq"><br>
               <span class="style57"></span></td>
             <td height="11" class="BordaInf style57">Outros</td>
             <td width="49" align="right" valign="bottom" class="BordaInf style58">.</td>
           </tr>
           <tr>
             <td height="24"> </td>
             <td colspan="6" class="BordaInfEsq">ASSINATURA DO RECEBEDOR</td>
             <td class="BordaInfEsq">DATA DE ENTREGA </td>
           </tr>
           <tr>
             <td> </td>
             <td colspan="6" class="BordaEsq">NOME LEGÍVEL DO RECEBEDOR</td>
             <td class="BordaEsq">Nº DOC. DE IDENTIDADE </td>
           </tr>
         </table>


';








if ( $tipoEnvio == 'free_shipping' ) {




} else {


$html .= $tipoEnvio;


}












if ( is_plugin_active( 'woocommerce-extra-checkout-fields-for-brazil/woocommerce-extra-checkout-fields-for-brazil.php' ) ) {


$numero  = $order->shipping_number;


$bairro  = $order->shipping_neighborhood;




}


















if($i == 13){


$html .= 'ssssss</page><page>';


$a=0;


}






$i++;






}












$html .= 'ssssss</page><page>';


$html .= ' </body>';


$html .= '</html>';






$dompdf = new DOMPDF();


$dompdf->load_html($html);


$dompdf->render();


$dompdf->stream("AR.pdf", array('Attachment'=>0));






exit;


}










function custom_admin_AR_js() {






if ( $_GET['gerada_ar'] == "1" ) {


    echo '<script type="text/javascript" language="Javascript">window.open("'. get_admin_url() .'admin-ajax.php/?action=get_AR_pdf&ids='.$_GET['ids'].'")</script>';


}


}










add_action('wp_ajax_get_AR_pdf', 'get_AR_pdf');


add_action('wp_ajax_nopriv_get_AR_pdf', 'get_AR_pdf');


add_action( 'admin_footer', 'bulk_admin_AR_footer', 1000 );


add_action( 'load-edit.php', 'bulk_action_AR' );


add_action( 'admin_notices', 'bulk_action_AR_notices' );


add_action('admin_head', 'custom_admin_AR_js');

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por daemon
      Boa tarde,
       
      Eu tenho uma rotina que faz uma leitura do arquivo .xml de vários sites.

      Eu consigo pegar o tópico e a descrição, e mostrar a imagem que esta na pagina do link.
      Para isso utilizo esta função:
      function getPreviewImage($url) { // Obter o conteúdo da página $html = file_get_contents($url); // Criar um novo objeto DOMDocument $doc = new DOMDocument(); @$doc->loadHTML($html); // Procurar pela tag meta og:image $tags = $doc->getElementsByTagName('meta'); foreach ($tags as $tag) { if ($tag->getAttribute('property') == 'og:image') { return $tag->getAttribute('content'); } } // Se não encontrar og:image, procurar pela primeira imagem na página $tags = $doc->getElementsByTagName('img'); if ($tags->length > 0) { return $tags->item(0)->getAttribute('src'); } // Se não encontrar nenhuma imagem, retornar null return null; } // Uso: $url = "https://example.com/article"; $imageUrl = getPreviewImage($url); if ($imageUrl) { echo "<img src='$imageUrl' alt='Preview'>"; } else { echo "Nenhuma imagem encontrada"; }  
      Mas estou com um problema, esta funcão funciona quando coloco em uma pagina de teste.php. Preciso mostrar em uma página inicial diversas fotos de todos os links. (No caso acima só funciona 1).
    • Por violin101
      Caros amigos, saudações.
       
      Por favor, me permita tirar uma dúvida com os amigos.

      Tenho um Formulário onde o Usuário digita todos os Dados necessários.

      Minha dúvida:
      --> como faço após o usuário digitar os dados e salvar, o Sistema chamar uma Modal ou mensagem perguntando se deseja imprimir agora ?

      Grato,
       
      Cesar
    • Por Carcleo
      Tenho uma abela de usuarios e uma tabela de administradores e clientes.
      Gostaria de uma ajuda para implementar um cadastro
       
      users -> name, login, passord (pronta) admins -> user_id, registratiom, etc.. client -> user_id, registratiom, etc...
      Queria ajuda para extender de user as classes Admin e Client
      Olhem como estáAdmin
      <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Admin extends User {     use HasFactory;            protected $fillable = [         'name',         'email',         'password',         'registration'     ];      private string $registration;     public function create(         string $name,          string $email,          string $password,         string $registration     )     {         //parent::create(['name'=>$name, 'email'=>$email, 'password'=>$password]);         parent::$name = $name;         parent::$email = $email;         parent::$password = $password;         $this->registration = $registration;     } } User
      <?php namespace App\Models; // use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Database\Eloquent\Relations\BelongsToMany; class User extends Authenticatable {     /** @use HasFactory<\Database\Factories\UserFactory> */     use HasFactory, Notifiable;     static string $name;     static string $email;     static string $password;     /**      * The attributes that are mass assignable.      *      * @var list<string>      */     protected $fillable = [         'name',         'email',         'password',     ];          /**      * The attributes that should be hidden for serialization.      *      * @var list<string>      */     protected $hidden = [         'remember_token',     ];     /**      * Get the attributes that should be cast.      *      * @return array<string, string>      */     protected function casts(): array     {         return [             'email_verified_at' => 'datetime',             'password' => 'hashed',         ];     }          public function roles() : BelongsToMany {         return $this->belongsToMany(Role::class);     }       public function hasHole(Array $roleName): bool     {                 foreach ($this->roles as $role) {             if ($role->name === $roleName) {                 return true;             }         }         return false;     }         public function hasHoles(Array $rolesName): bool     {                 foreach ($this->roles as $role) {             foreach ($rolesName as $rolee) {             if ($role->name === $rolee) {                 return true;             }          }         }         return false;     }         public function hasAbility(string $ability): bool     {         foreach ($this->roles as $role) {             if ($role->abilities->contains('name', $ability)) {                 return true;             }         }         return false;     }     } Como gravar um Admin na tabela admins sendo que ele é um User por extensão?
      Tentei assim mas é claro que está errado...
      public function store(Request $request, Admin $adminModel) {         $dados = $request->validate([             "name" => "required",             "email" => "required|email",             "password" => "required",             "registration" => "required"         ]);         $dados["password"] =  Hash::make($dados["password"]);                  $admin = Admin::where("registration",  $dados["registration"])->first();                  if ($admin)              return                    redirect()->route("admin.new")                             ->withErrors([                                 'fail' => 'Administrador já cadastrados<br>, favor verificar!'                   ]);                            $newAdmin = $adminModel->create(                                    $dados['name'],                                    $dados['email'],                                    $dados['password'],                                    $dados['registration']                                 );         dd($newAdmin);         $adminModel->save();         //$adminModel::create($admin);                  return redirect()->route("admin.new")->with("success",'Cadastrado com sucesso');     }  
    • Por violin101
      Caros amigos, saudações.
       
      Gostaria de tirar uma dúvida com os amigos, referente a PDV.
       
      Estou escrevendo um Sistema com Ponto de Vendas, a minha dúvida é o seguinte, referente ao procedimento mais correto.

      Conforme o caixa vai efetuando a venda, o Sistema de PDV já realiza:
      a baixa direto dos produtos no estoque
      ou
      somente após concretizar a venda o sistema baixa os produtos do estoque ?
       
      Grato,
       
      Cesar
       
    • Por violin101
      Caros amigos do grupo, saudações e um feliz 2025.
       
      Estou com uma pequena dúvida referente a Teclas de Atalho.

      Quando o Caps Lock está ativado o Comando da Tecla de Atalho não funciona.
      ou seja:
      se estiver para letra minúscula ====> funciona
      se estiver para letra maiúscula ====> não funciona
       
      Como consigo evitar essa falha, tanto para Letra Maiúscula quanto Minúscula ?

      o Código está assim:
      document.addEventListener( 'keydown', evt => { if (!evt.ctrlKey || evt.key !== 'r' ) return;// Não é Ctrl+r, portanto interrompemos o script evt.preventDefault(); });  
      Grato,
       
      Cesar
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.