Last active
October 17, 2019 14:54
-
-
Save MirandinhaKL/f67d42d1b19052cb0c43a25d8c83d463 to your computer and use it in GitHub Desktop.
PDF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Ergonomia.Banco; | |
using Ergonomia.Classes; | |
using iTextSharp.text; | |
using iTextSharp.text.pdf; | |
using System; | |
using System.Collections.Generic; | |
//using System.Drawing; | |
using System.IO; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Windows.Forms; | |
using static iTextSharp.text.Font; | |
using Font = iTextSharp.text.Font; | |
/* | |
* Criado em: 16/09/2019 | |
* Última alteração: 19/09/2019 | |
*/ | |
namespace Ergonomia.PDFs | |
{ | |
/// <summary> | |
/// Gera um arquivo em PDF referente ao formulário de melhoria ergonômica. | |
/// </summary> | |
public class Formulario_Melhoria_Ergonomica | |
{ | |
private Document documento = new Document(PageSize.A4); | |
/// <summary> | |
/// Gera um arquivo em PDF contendo as informações referentes ao formulário de melhoria ergonômica. | |
/// </summary> | |
/// <param name="saveFile"></param> | |
/// <param name="id_registro"></param> | |
/// <returns></returns> | |
public string obtem_formulario(SaveFileDialog saveFile, int cod_registro) | |
{ | |
try | |
{ | |
// Obtem dados do registro ergonômico: | |
Banco_registro_ergonomico conexao_registro = new Banco_registro_ergonomico(); | |
Registro_ergonomico registro = conexao_registro.obtem_um_registro(cod_registro); | |
Banco_registro_risco_inicial conexao_riscos = new Banco_registro_risco_inicial(); | |
List<Registro_risco_inicial> lista_riscos = conexao_riscos. | |
obtem_fator_risco_por_registro(cod_registro); | |
// Configura o pdf: | |
inicializa_pdf(saveFile); | |
insere_logotipo(); | |
gera_cabecalho_pdf("FORMULÁRIO DE MELHORIA ERGONÔMICA: AET-" + registro.codigo_registro); | |
insere_texto_negrito_e_normal("- EMPRESA: ", registro.empresa_.nome); | |
insere_texto_negrito_e_normal("- ÁREA/SETOR: ", registro.area_.nome); | |
insere_texto_negrito_e_normal("- TAREFA HOMOGÊNEA: ", registro.aet_.descricao); | |
insere_texto_negrito_e_normal("- NATUREZA DA TAREFA: ", configura_regiao_do_corpo(registro.aet_.natureza)); | |
insere_texto_negrito_e_normal("- INDICADOR DE VULNERABILIDADE: ", registro.indicador_inicial.ToString() + "%"); | |
insere_texto_negrito_e_normal("- FATORES DE RISCO PRESENTES NA TAREFA ANALISADA: ", ""); | |
for (int i = 0; i < lista_riscos.Count; i++) | |
{ | |
insere_texto_negrito_e_normal(" ", i + 1 + "- " + lista_riscos[i].fator_inicial_.descricao); | |
} | |
insere_texto_negrito_e_normal("- AÇÕES PROPOSTAS (HIERARQUIA DE CONTROLE: )", ""); | |
insere_texto_negrito_e_normal("", registro.sugestao); | |
insere_texto_negrito_e_normal("- PRAZO ESTIMADO PARA A CONCLUSÃO DOS PROJETOS: ", | |
registro.data_verificacao.ToShortDateString() + " (" + registro.prazo_adequacao + " dias)"); | |
documento.NewPage(); | |
insere_logotipo(); | |
gera_cabecalho_pdf("TERMO DE RECONHECIMENTO"); | |
insere_texto_padrao(" Eu, " + registro.responsavel + ", responsável direto por organizar " + | |
"e definir um plano de ação definitivo com base nas ações propostas pela AET-" + | |
registro.codigo_registro + ", venho através desse reconhecer o recebimento das " + | |
"informações técnicas repassadas, fatores de risco encontrados e prazos estipulados. " + | |
"Juntamente com a equipe de trabalho serão desenvolvidas as ações focadas na segurança, " + | |
"produtividade e conforto dos operadores.", ""); | |
insere_texto_centralizado(""); | |
insere_texto_centralizado(""); | |
insere_texto_centralizado(""); | |
insere_texto_centralizado("__________________________________________"); | |
insere_texto_centralizado(registro.responsavel); | |
insere_texto_centralizado(""); | |
insere_texto_centralizado(""); | |
insere_texto_a_direita("Caxias do Sul, " + DateTime.Now.ToLongDateString()); | |
documento.Close(); | |
System.Diagnostics.Process.Start(saveFile.FileName + ".pdf"); | |
return "1"; | |
} | |
catch (Exception excecao) | |
{ | |
return "Erro 44: " + excecao.Message; | |
} | |
} | |
/// <summary> | |
/// Dada uma certa natureza da tarefa homogênea, uma determinada | |
/// área do corpo é afetada. | |
/// </summary> | |
/// <param name="natureza"></param> | |
/// <returns></returns> | |
private string configura_regiao_do_corpo(string natureza) | |
{ | |
string condicao1 = "PUXAR/EMPURRAR."; | |
string condicao2 = "LEVANTAMENTO MANUAL DE CARGAS."; | |
string condicao3 = "REPETITIVIDADE DE MEMBROS SUPERIORES, COM PADRÃO CÍCLICO."; | |
string condicao4 = "VARIAÇÃO DE GESTOS TÉCNICOS, SEM PADRÃO CÍCLICO, COM EVIDÊNCIA POSTURAL REPRESENTATIVA."; | |
string regiao = ""; | |
if (natureza == condicao1) | |
{ | |
regiao = "OMBRO E COLUNA LOMBAR"; | |
} | |
if (natureza == condicao2) | |
{ | |
regiao = "COLUNA LOMBAR"; | |
} | |
if (natureza == condicao3) | |
{ | |
regiao = "MEMBROS SUPERIORES"; | |
} | |
if (natureza == condicao4) | |
{ | |
regiao = "DEPENDE DA ANÁLISE, POR TER RELAÇÃO COM TODOS OS SEGMENTOS CORPORAIS."; | |
} | |
return regiao; | |
} | |
/// <summary> | |
/// Cria e configura o arquivo em PDF. | |
/// </summary> | |
/// <param name="sfd_"></param> | |
/// <returns></returns> | |
private Document inicializa_pdf(SaveFileDialog saveFile) | |
{ | |
documento.SetMargins(40, 40, 20, 80); | |
documento.AddCreationDate(); | |
string caminho_relatorio = saveFile.FileName + ".pdf"; | |
PdfWriter pdf = PdfWriter.GetInstance(documento, new FileStream(caminho_relatorio, | |
FileMode.Create)); | |
documento.Open(); | |
return documento; | |
} | |
private void insere_logotipo() | |
{ | |
iTextSharp.text.Image logotipo = Image.GetInstance(Directory.GetCurrentDirectory() + @"\imagens\logo.jpg"); | |
logotipo.ScalePercent(50f); | |
logotipo.Alignment = Element.ALIGN_CENTER; | |
documento.Add(logotipo); | |
} | |
/// <summary> | |
/// Insere cabeçalho no relatório. | |
/// </summary> | |
private void gera_cabecalho_pdf(string titulo) | |
{ | |
BaseFont base_titulo = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false); | |
Font fonte_titulo_relatorio = new Font(base_titulo, 11, Font.BOLD); | |
Paragraph paragrafo = new Paragraph(titulo, new Font(fonte_titulo_relatorio)); | |
paragrafo.Alignment = Element.ALIGN_CENTER; | |
paragrafo.SpacingAfter = 30f; | |
documento.Add(paragrafo); | |
} | |
/// <summary> | |
/// Adiciona no pdf texto alinhado a direita. | |
/// </summary> | |
private void insere_texto_padrao(string titulo, string texto) | |
{ | |
BaseFont base_titulo = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false); | |
Font fonte_titulo = new Font(base_titulo, 12, Font.NORMAL); | |
Paragraph paragrafo = new Paragraph(titulo + texto, new Font(fonte_titulo)); | |
paragrafo.SpacingAfter = 10f; | |
paragrafo.Alignment = Element.ALIGN_JUSTIFIED; | |
documento.Add(paragrafo); | |
} | |
private void insere_texto_centralizado(string texto) | |
{ | |
BaseFont base_titulo = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false); | |
Font fonte_titulo = new Font(base_titulo, 12, Font.NORMAL); | |
Paragraph paragrafo = new Paragraph(texto, new Font(fonte_titulo)); | |
paragrafo.SpacingAfter = 10f; | |
paragrafo.Alignment = Element.ALIGN_CENTER; | |
documento.Add(paragrafo); | |
} | |
private void insere_texto_a_direita(string texto) | |
{ | |
BaseFont base_titulo = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false); | |
Font fonte_titulo = new Font(base_titulo, 12, Font.NORMAL); | |
Paragraph paragrafo = new Paragraph(texto, new Font(fonte_titulo)); | |
paragrafo.SpacingAfter = 10f; | |
paragrafo.Alignment = Element.ALIGN_RIGHT; | |
documento.Add(paragrafo); | |
} | |
/// <summary> | |
/// Insere uma primeira sentença em negrito e a segunda . texto normal; | |
/// </summary> | |
/// <param name="destaque"></param> | |
/// <param name="texto"></param> | |
private void insere_texto_negrito_e_normal(string destaque, string texto) | |
{ | |
Font fonte1 = new Font(FontFamily.HELVETICA, 12, Font.BOLD, BaseColor.BLACK); | |
Font fonte2 = new Font(FontFamily.HELVETICA, 12, Font.NORMAL, BaseColor.BLACK); | |
Chunk fragmento1 = new Chunk(destaque, fonte1); | |
Chunk fragmento2 = new Chunk(texto, fonte2); | |
Phrase frase1 = new Phrase(); | |
frase1.Add(fragmento1); | |
frase1.Add(fragmento2); | |
Paragraph paragrafo = new Paragraph(); | |
paragrafo.SpacingAfter = 10f; | |
paragrafo.Alignment = Element.ALIGN_JUSTIFIED; | |
paragrafo.Add(frase1); | |
documento.Add(paragrafo); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using iTextSharp.text; | |
using iTextSharp.text.pdf; | |
using Npgsql; | |
using principal.classes; | |
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Windows.Forms; | |
// Instalar o Nuget do iText. | |
namespace principal.conexao_banco | |
{ | |
/// <summary> | |
/// Contém os métodos necessários para consultar o banco de dados e imprimir um aquivo em pdf. | |
/// </summary> | |
public class banco_relatorio_pdf | |
{ | |
private Document relatorio_listas = new Document(PageSize.A4); | |
/// <summary> | |
/// Realiza a consulta no banco de dados, e com os filtros informados pelo usuário, retorna os dados | |
/// em um arquivo no formato pdf. | |
/// </summary> | |
/// <param name="query_sql">Comando que será utilizado para a consutla no banco.</param> | |
/// <param name="descricao_tabela">Título da tabela que estará contida no arquivo em pff.</param> | |
/// <param name="save_file_dialog_">Contém o endereço onde será salvo e o nome do PDF.</param> | |
/// <returns></returns> | |
public int retorna_arquivo_pdf(string query_sql, string descricao_tabela, SaveFileDialog save_file_dialog_) | |
{ | |
// Criando e configurando o arquivo pdf. | |
try | |
{ | |
inicializa_pdf(save_file_dialog_); | |
gera_cabecalho_pdf(); | |
cria_tabela_no_pdf(descricao_tabela); | |
float[] largura_colunas = { 50, 120, 150, 85, 65, 80 }; | |
PdfPTable tabela_dados = new PdfPTable(largura_colunas); | |
tabela_dados.TotalWidth = 550f; | |
tabela_dados.LockedWidth = true; | |
// Obtendo os dados do banco. | |
List<quant_produto_posto> lista_quantidade = new List<quant_produto_posto>(); | |
try | |
{ | |
conexao nova_conexao = new conexao(); | |
using (NpgsqlConnection conexao = new NpgsqlConnection(nova_conexao.string_conexao)) | |
{ | |
conexao.Open(); | |
NpgsqlCommand comando = conexao.CreateCommand(); | |
comando.CommandText = query_sql; | |
NpgsqlDataReader resultado = comando.ExecuteReader(); | |
while (resultado.Read()) | |
{ | |
tabela_dados.AddCell(formata_dado_coluna(resultado["codigo_posto"].ToString())); | |
tabela_dados.AddCell(new Phrase(resultado["nm_login"].ToString(), new Font(Font.NORMAL, 10f))); | |
tabela_dados.AddCell(new Phrase(resultado["nome_produto"].ToString(), new Font(Font.NORMAL, 10f))); | |
tabela_dados.AddCell(formata_dado_coluna(resultado["codigo_barras"].ToString())); | |
tabela_dados.AddCell(formata_dado_coluna(resultado["quantidade"].ToString())); | |
tabela_dados.AddCell(formata_dado_coluna(resultado["data_inserida"].ToString())); | |
} | |
relatorio_listas.Add(tabela_dados); | |
relatorio_listas.Close(); | |
System.Diagnostics.Process.Start(save_file_dialog_.FileName + ".pdf"); | |
} | |
return 89; | |
} | |
catch (Exception excecao) | |
{ | |
var erro = excecao.Message; | |
return -1; | |
} | |
} | |
catch (Exception excecao) | |
{ | |
var erro = excecao.Message; | |
return -2; | |
} | |
} | |
/// <summary> | |
/// Cria e configura o arquivo em PDF. | |
/// </summary> | |
/// <param name="sfd_"></param> | |
/// <returns></returns> | |
public Document inicializa_pdf(SaveFileDialog sfd_) | |
{ | |
relatorio_listas.SetMargins(20, 20, 20, 80); | |
relatorio_listas.AddCreationDate(); | |
string caminho_relatorio = sfd_.FileName + ".pdf"; | |
PdfWriter pdf = PdfWriter.GetInstance(relatorio_listas, new FileStream(caminho_relatorio, FileMode.Create)); | |
relatorio_listas.Open(); | |
Image logotipo_sim = Image.GetInstance(Directory.GetCurrentDirectory() + @"\imagens\postos_sim.png"); | |
logotipo_sim.ScalePercent(30f); | |
logotipo_sim.Alignment = Element.ALIGN_CENTER; | |
relatorio_listas.Add(logotipo_sim); | |
return relatorio_listas; | |
} | |
/// <summary> | |
/// Insere cabeçalho no relatório. | |
/// </summary> | |
public void gera_cabecalho_pdf() | |
{ | |
BaseFont base_titulo = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false); | |
Font fonte_titulo_relatorio = new Font(base_titulo, 11, Font.BOLD); | |
string titulo = "Relatório de Erros Contagem Cíclica: " + DateTime.Today.ToShortDateString() + ""; | |
Paragraph paragrafo = new Paragraph(titulo, new Font(fonte_titulo_relatorio)); | |
paragrafo.Alignment = Element.ALIGN_CENTER; | |
paragrafo.SpacingAfter = 30f; | |
relatorio_listas.Add(paragrafo); | |
} | |
/// <summary> | |
/// Cria a tabela que contém os dados que serão exibidos no relatório. | |
/// </summary> | |
/// <param name="descricao_tabela"></param> | |
public void cria_tabela_no_pdf(string descricao_tabela) | |
{ | |
float[] largura_colunas = { 50, 120, 150, 85, 65, 80 }; | |
PdfPTable tabela = new PdfPTable(largura_colunas); | |
tabela.TotalWidth = 550f; | |
tabela.LockedWidth = true; | |
PdfPCell coluna = new PdfPCell(new Phrase(descricao_tabela)); | |
coluna.Colspan = 6; | |
coluna.PaddingTop = 5f; | |
coluna.PaddingBottom = 10f; | |
coluna.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right | |
coluna.VerticalAlignment = 1; | |
coluna.BackgroundColor = new BaseColor(211, 211, 211); | |
tabela.AddCell(coluna); | |
tabela.AddCell(formata_titulo_coluna("Código do posto")); | |
tabela.AddCell(formata_titulo_coluna("Nome do posto")); | |
tabela.AddCell(formata_titulo_coluna("Nome dos produtos")); | |
tabela.AddCell(formata_titulo_coluna("Código de barras")); | |
tabela.AddCell(formata_titulo_coluna("Quantidade preenchida")); | |
tabela.AddCell(formata_titulo_coluna("Data preenchimento")); | |
relatorio_listas.Add(tabela); | |
} | |
/// <summary> | |
/// Formata cor e alinhamento do título das colunas de uma tabela. | |
/// </summary> | |
/// <param name="titulo_coluna"></param> | |
/// <returns></returns> | |
public PdfPCell formata_titulo_coluna(string titulo_coluna) | |
{ | |
PdfPCell coluna = new PdfPCell(new Phrase(titulo_coluna, new Font(Font.FontFamily.HELVETICA, 10f, Font.BOLD))); | |
coluna.HorizontalAlignment = 1; | |
coluna.VerticalAlignment = Element.ALIGN_MIDDLE; | |
coluna.BackgroundColor = new BaseColor(240, 240, 240); | |
return coluna; | |
} | |
/// <summary> | |
/// Centraliza horizontalmente os dados de umma coluna e formata o tamanho da fonte. | |
/// </summary> | |
/// <param name="retorno_banco"></param> | |
/// <returns></returns> | |
public PdfPCell formata_dado_coluna(string retorno_banco) | |
{ | |
PdfPCell coluna = new PdfPCell(new Phrase(retorno_banco, new Font(Font.NORMAL, 10f))); | |
coluna.HorizontalAlignment = 1; | |
return coluna; | |
} | |
} | |
} | |
// ============================================================================================================ | |
/// <summary> | |
/// Através dos filtros selecionados e informados pelo usuário, é gerado um relatótrio no formato PDF. | |
/// </summary> | |
public void gera_relatorio() | |
{ | |
if (check_codigo_lista.Checked || check_codigo_posto.Checked || check_data_preenhcimento.Checked) | |
{ | |
if (codigo_filtro_foi_informado()) | |
{ | |
if (habilita_save_file_dialog(sfd_relatorio)) | |
{ | |
string comando_sql = seleciona_comando_sql_relatorio_pdf(); | |
string descricao_tabela = define_descricao_tabela_relatorio(); | |
this.Cursor = Cursors.WaitCursor; | |
banco_relatorio_pdf conexao_relatorio = new banco_relatorio_pdf(); | |
int resultado = conexao_relatorio.retorna_arquivo_pdf(comando_sql, descricao_tabela, sfd_relatorio); | |
metodo.informa_erro_gerar_relatorio(resultado); | |
metodo.informa_erro_banco_dados(resultado, 89); | |
if (resultado > 0) | |
{ | |
check_codigo_lista.Checked = false; | |
check_codigo_posto.Checked = false; | |
check_data_preenhcimento.Checked = false; | |
txt_codigo_lista.Clear(); | |
txt_codigo_posto.Clear(); | |
} | |
this.Cursor = Cursors.Default; | |
} | |
} | |
} | |
else | |
{ | |
MessageBox.Show("Por favor, selecione um filtro para gerar o relatório (código da lista, código do posto " + | |
"ou data de preenchimento).", "Status da ação", MessageBoxButtons.OK, MessageBoxIcon.Information); | |
} | |
} | |
private bool habilita_save_file_dialog(SaveFileDialog sfd_) | |
{ | |
string data = DateTime.Today.ToShortDateString(); | |
string[] temporario = data.Split('/'); | |
string data_formatada = temporario[0] + temporario[1] + temporario[2]; | |
sfd_.Filter = "PDF(*.pdf)|*pdf"; | |
sfd_.FileName = "Relatório CC - " + data_formatada; | |
bool resultado = sfd_.ShowDialog() == DialogResult.OK ? true : false; | |
return resultado; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment