Inquiridor
Imprimir PDF

Pergunta
-
Todas as Respostas
-
Criei o seguinte método:
private void ImprimirPdf(string strPathExeAdobeReader, string strDiretorioOndeEstaoPdfs, string strNomeArquivoPdf, string strNomeImpressora) { if (string.IsNullOrEmpty(strPathExeAdobeReader)) throw new Exception("Nenhum caminho (path) para o arquivo AcroRd32.exe / Acrobat.exe encontrado."); if (string.IsNullOrEmpty(strNomeImpressora)) throw new Exception("Nenhuma impressora encontrada."); if (string.IsNullOrEmpty(strDiretorioOndeEstaoPdfs)) throw new Exception("O caminho para o diretórios dos arquivos PDF´s não foi encontrado."); else { string strPathArqPdf = Path.Combine(strDiretorioOndeEstaoPdfs, strNomeArquivoPdf); if (!File.Exists(strPathArqPdf)) throw new Exception(String.Format("O arquivo {0} não existe.", strPathArqPdf)); } ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = strPathExeAdobeReader; string args = String.Format("/t \"{0}\" \"{1}\"", strNomeArquivoPdf, strNomeImpressora); startInfo.Arguments = args; startInfo.CreateNoWindow = true; startInfo.ErrorDialog = false; startInfo.UseShellExecute = false; startInfo.WorkingDirectory = strDiretorioOndeEstaoPdfs; Process process = Process.Start(startInfo); process.WaitForInputIdle(); }
Estou utilizando este método em uma aplicação Windows Forms, da seguinte forma:
private void btnImprimir_Click(object sender, EventArgs e) { string strNomeImpressora = string.Empty; if (pdlImpressoras.ShowDialog() == DialogResult.OK) strNomeImpressora = pdlImpressoras.PrinterSettings.PrinterName; string strPathAcrobatReader = @"C:\Program Files (x86)\Adobe\Reader 9.0\Reader\AcroRd32.exe"; string strDiretorioComPdfs = @"D:\Danfe-Pdf"; string strNomeArquivoPdf = "00000000000000000000000000000000000000000000-danfe.pdf"; ImprimirPdf(strPathAcrobatReader, strDiretorioComPdfs, strNomeArquivoPdf, strNomeImpressora); }
O item pdlImpresoras é um componente PrintDialog do próprio Visual Studio 2008. Fica na aba Printing.
[]´s
Drausio Henrique Chiarotti -
Para complementar o tópico, tinha uma aplicação que utilizava ReportViewer.LocalReport, e esta aplicação convertia (renderizava) para PDF. Ao invés de converter para PDF, adicionei a implementação abaixo, para imprimir direto sem abrir o preview.
No meu caso ficou legal, pois mantive o relatório PDF e fiz uns ajustes para imprimir direto quando necessário.
//Fonte: http://msdn.microsoft.com/en-us/library/ms252091(VS.80).aspx private int m_currentPageIndex; private IList<Stream> m_streams; // Export the given report as an EMF (Enhanced Metafile) file. private void Export(LocalReport report) { //Papel A4 = Largura 8.5in (polegadas) e Altura 11in (polegadas). string deviceInfo = "<DeviceInfo>" + " <OutputFormat>EMF</OutputFormat>" + " <PageWidth>8.5in</PageWidth>" + " <PageHeight>11in</PageHeight>" + " <MarginTop>0.05in</MarginTop>" + " <MarginLeft>0.25in</MarginLeft>" + " <MarginRight>0.25in</MarginRight>" + " <MarginBottom>0.00in</MarginBottom>" + "</DeviceInfo>"; Warning[] warnings; m_streams = new List<Stream>(); report.Render("Image", deviceInfo, CreateStream, out warnings); foreach (Stream stream in m_streams) stream.Position = 0; } private Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek) { Stream stream = new MemoryStream(); //Stream stream = new FileStream(@"..\..\" + name + DateTime.Now.ToString("dd-MM-yyyy_HH-mm-ss") + "." + fileNameExtension, FileMode.Create); m_streams.Add(stream); return stream; } private string Print(string printerName) { try { if (m_streams == null || m_streams.Count == 0) return "Nenhum relatório encontrado!"; PrintDocument printDoc = new PrintDocument(); printDoc.PrinterSettings.PrinterName = printerName; if (!printDoc.PrinterSettings.IsValid) { return String.Format("Can't find printer \"{0}\".", printerName); } printDoc.PrintPage += new PrintPageEventHandler(PrintPage); printDoc.Print(); return string.Empty; } catch (Exception ex) { return ex.Message; } } private void PrintPage(object sender, PrintPageEventArgs ev) { Metafile pageImage = new Metafile(m_streams[m_currentPageIndex]); ev.Graphics.DrawImage(pageImage, ev.PageBounds); m_currentPageIndex++; ev.HasMorePages = (m_currentPageIndex < m_streams.Count); } /* * Para pegar o nome da impressora, pode utilizar o componente PrintDialog * * if (pdlImpressoras.ShowDialog() == DialogResult.OK) strNomeImpressora = pdlImpressoras.PrinterSettings.PrinterName; */ public string Imprimir(LocalReport lcrRelatorio, string strNomeImpressora) { try { Export(lcrRelatorio); m_currentPageIndex = 0; return Print(strNomeImpressora); } catch (Exception ex) { return ex.Message; } }
[]´s
Drausio Henrique Chiarotti -
Oi,
As sugestões dadas de impressão nas outras mensagens ou são especificas para windows forms ou fariam com que a impressão ocorresse no lado do servidor, ao invés de ocorrer no client.
O problema em relação a essa impressão é que o client - via browser - não permite que você tenha grande acesso aos recursos da máquina client, trata-se de uma questão de segurança. Usar os recursos de impressão do framework causaria na melhor das hipóteses a impressão no lado do servidor, mas não do lado do client
[]'sDennes
http://twitter.com/Dennes* Treinamento C# e Framework .NET c/OO dia 12/12 - Apenas 12 R$ 42,53 Inscreva-se em http://www.bufaloinfo.com.br/cursos/fundamentosOOFramework.asp
* Treinamento de ASP.NET 3.5 no RJ dia 16/01 - Apenas 12x R$ 60,48 - Inscreva-se em http://www.bufaloinfo.com.br/descontoaspnetantecipado.asp
Tel : (11) 3170-3056 (21)9240-5134 E-Mail: contato arroba bufaloinfo.com.br
http://www.bufaloinfo.com.br
Dennes - Se resolveu, classifique a mensagem, por favor - [http://www.bufaloinfo.com.br] NOVO DVD Segurança no ASP.NET : http://www.bufaloinfo.com.br/LearingSeriesSegurancaASPNET2.asp