Scriptcase + Cloud2Pdf

Integração completa para geração de PDFs em aplicações Scriptcase

🚀 PHP Native 📊 Grid/Forms ⚡ cURL Ready

🚀 Quick Start

1

Configurar Variáveis Globais

No Scriptcase, vá em Configurações → Variáveis Globais

$cloud2pdf_api_url = 'https://api.cloud2pdf.com/v1'; $cloud2pdf_api_token = 'seu_token_aqui';
2

Criar Biblioteca Cloud2Pdf

Crie uma Biblioteca com funções reutilizáveis

3

Usar em Grid/Form

Chame a função da biblioteca em eventos

📚 Biblioteca Cloud2Pdf

Crie uma Biblioteca no Scriptcase com as funções abaixo:

<?php // Biblioteca: lib_cloud2pdf /** * Gera PDF de forma assíncrona */ function cloud2pdf_generate_async($html, $reference = null, $options = []) { global $cloud2pdf_api_url, $cloud2pdf_api_token; $data = [ 'html' => $html, 'is_disk' => true, 'reference' => $reference, 'options' => array_merge([ 'format' => 'A4', 'landscape' => false, ], $options) ]; $ch = curl_init($cloud2pdf_api_url . '/pdf/generate-async'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer ' . $cloud2pdf_api_token, 'Content-Type: application/json', 'Accept: application/json' ]); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpCode != 202) { return ['error' => 'Failed to generate PDF', 'code' => $httpCode]; } return json_decode($response, true); } /** * Verifica status do PDF */ function cloud2pdf_check_status($pdf_id) { global $cloud2pdf_api_url, $cloud2pdf_api_token; $ch = curl_init($cloud2pdf_api_url . '/pdf/status/' . $pdf_id); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer ' . $cloud2pdf_api_token, 'Accept: application/json' ]); $response = curl_exec($ch); curl_close($ch); return json_decode($response, true); } /** * Aguarda conclusão do PDF */ function cloud2pdf_wait_completion($pdf_id, $max_attempts = 60, $delay = 5) { for ($i = 0; $i < $max_attempts; $i++) { $status = cloud2pdf_check_status($pdf_id); if ($status['status'] == 'completed') { return $status; } if ($status['status'] == 'failed') { return ['error' => 'PDF generation failed']; } sleep($delay); } return ['error' => 'Timeout waiting for PDF']; } /** * Download do PDF */ function cloud2pdf_download($pdf_id) { global $cloud2pdf_api_url, $cloud2pdf_api_token; $ch = curl_init($cloud2pdf_api_url . '/pdf/download/' . $pdf_id); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer ' . $cloud2pdf_api_token ]); $content = curl_exec($ch); curl_close($ch); return $content; } /** * Gera PDF síncrono (apenas PDFs pequenos!) */ function cloud2pdf_generate_sync($html, $options = []) { global $cloud2pdf_api_url, $cloud2pdf_api_token; $data = [ 'html' => $html, 'is_disk' => false, 'options' => $options ]; $ch = curl_init($cloud2pdf_api_url . '/pdf/generate'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer ' . $cloud2pdf_api_token, 'Content-Type: application/json', 'Accept: application/json' ]); $response = curl_exec($ch); curl_close($ch); return json_decode($response, true); } ?>

📊 Exemplo em Grid

Adicione um botão no Grid para gerar PDF de um relatório

1. Criar Botão no Grid

Grid → Botões da Aplicação → Novo Botão

// Evento onClick do botão "Gerar PDF" sc_include_library('lib_cloud2pdf'); // Buscar dados $id = {id}; // Campo do grid $query = "SELECT * FROM invoices WHERE id = $id"; sc_lookup(rs, $query); if (isset({rs[0][0]})) { // Montar HTML $html = '<h1>Invoice #' . {rs[0]['invoice_number']} . '</h1>'; $html .= '<p>Customer: ' . {rs[0]['customer_name']} . '</p>'; $html .= '<p>Amount: $' . {rs[0]['amount']} . '</p>'; // Gerar PDF assíncrono $result = cloud2pdf_generate_async($html, "invoice-$id"); if (isset($result['pdf_id'])) { // Salvar PDF ID no banco $pdf_id = $result['pdf_id']; $update = "UPDATE invoices SET pdf_id = $pdf_id, pdf_status = 'processing' WHERE id = $id"; sc_exec_sql($update); sc_alert('PDF generation started! ID: ' . $pdf_id); sc_redir($this->Ini->nm_ger_fil_nome); // Recarrega grid } else { sc_alert('Error generating PDF'); } }

2. Botão para Download

// Evento onClick do botão "Download PDF" sc_include_library('lib_cloud2pdf'); $id = {id}; $query = "SELECT pdf_id FROM invoices WHERE id = $id"; sc_lookup(rs, $query); if (isset({rs[0][0]}) && !empty({rs[0]['pdf_id']})) { $pdf_id = {rs[0]['pdf_id']}; // Verificar status $status = cloud2pdf_check_status($pdf_id); if ($status['status'] == 'completed') { // Download $pdf_content = cloud2pdf_download($pdf_id); header('Content-Type: application/pdf'); header('Content-Disposition: attachment; filename="invoice-' . $id . '.pdf"'); echo $pdf_content; exit; } else { sc_alert('PDF still processing... Status: ' . $status['status']); } } else { sc_alert('No PDF generated for this record'); }

📝 Exemplo em Form

Gerar PDF após inserir/atualizar registro

// Evento onAfterInsert ou onAfterUpdate sc_include_library('lib_cloud2pdf'); // Montar HTML com dados do form $html = '<!DOCTYPE html>'; $html .= '<html><head><meta charset="UTF-8"></head><body>'; $html .= '<h1>Invoice #' . {invoice_number} . '</h1>'; $html .= '<p><strong>Customer:</strong> ' . {customer_name} . '</p>'; $html .= '<p><strong>Date:</strong> ' . {invoice_date} . '</p>'; $html .= '<p><strong>Amount:</strong> $' . {amount} . '</p>'; $html .= '</body></html>'; // Gerar PDF $result = cloud2pdf_generate_async($html, 'invoice-' . {id}, [ 'format' => 'A4', 'landscape' => false, 'margins' => [ 'top' => '20mm', 'right' => '15mm', 'bottom' => '20mm', 'left' => '15mm' ] ]); if (isset($result['pdf_id'])) { // Atualizar registro com PDF ID $pdf_id = $result['pdf_id']; $query = "UPDATE invoices SET pdf_id = $pdf_id, pdf_status = 'processing' WHERE id = " . {id}; sc_exec_sql($query); sc_alert('PDF generation started successfully!'); }

🎯 Blank Application (API Completa)

Crie uma Blank Application para controle total

<?php // Blank Application: pdf_generator // Incluir biblioteca sc_include_library('lib_cloud2pdf'); // Parâmetros via GET/POST $record_id = $_GET['id'] ?? 0; $action = $_GET['action'] ?? 'generate'; if ($record_id > 0) { // Buscar dados $query = "SELECT * FROM invoices WHERE id = $record_id"; sc_lookup(rs, $query); if (!isset({rs[0][0]})) { echo json_encode(['error' => 'Record not found']); exit; } $data = {rs[0]}; switch ($action) { case 'generate': // Montar HTML $html = render_invoice_html($data); // Gerar PDF $result = cloud2pdf_generate_async($html, "invoice-$record_id"); if (isset($result['pdf_id'])) { // Salvar no banco $update = "UPDATE invoices SET pdf_id = {$result['pdf_id']}, pdf_status = 'processing' WHERE id = $record_id"; sc_exec_sql($update); echo json_encode($result); } else { echo json_encode(['error' => 'Failed to generate PDF']); } break; case 'status': $pdf_id = $data['pdf_id'] ?? 0; if ($pdf_id > 0) { $status = cloud2pdf_check_status($pdf_id); echo json_encode($status); } else { echo json_encode(['error' => 'No PDF ID']); } break; case 'download': $pdf_id = $data['pdf_id'] ?? 0; if ($pdf_id > 0) { $content = cloud2pdf_download($pdf_id); header('Content-Type: application/pdf'); header('Content-Disposition: attachment; filename="invoice-' . $record_id . '.pdf"'); echo $content; exit; } break; } } else { echo json_encode(['error' => 'Invalid record ID']); } function render_invoice_html($data) { $html = '<!DOCTYPE html>'; $html .= '<html><head><meta charset="UTF-8"></head><body>'; $html .= '<h1>Invoice #' . $data['invoice_number'] . '</h1>'; $html .= '<p>Customer: ' . $data['customer_name'] . '</p>'; $html .= '<p>Amount: $' . $data['amount'] . '</p>'; $html .= '</body></html>'; return $html; } ?>

💡 Dicas

Use Variáveis Globais

Configure API URL e Token nas variáveis globais do Scriptcase

Crie uma Biblioteca Reutilizável

Centralize as funções para usar em múltiplos Grids/Forms

Salve o pdf_id no Banco

Adicione campo pdf_id nas suas tabelas para rastreamento

Use Blank Applications para APIs

Para controle total, crie Blank Applications dedicadas