-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathDanfe.cs
261 lines (204 loc) · 9.25 KB
/
Danfe.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
using System;
using System.Collections.Generic;
using DanfePDF.Blocos;
using org.pdfclown.documents;
using org.pdfclown.documents.contents.fonts;
using org.pdfclown.files;
using DanfePDF.Modelo;
namespace DanfePDF
{
public class Danfe : IDisposable
{
public DanfeViewModel ViewModel { get; private set; }
public File File { get; private set; }
internal Document PdfDocument { get; private set; }
internal BlocoCanhoto Canhoto { get; private set; }
internal BlocoIdentificacaoEmitente IdentificacaoEmitente { get; private set; }
internal List<BlocoBase> _Blocos;
internal Estilo EstiloPadrao { get; private set; }
internal List<DanfePagina> Paginas { get; private set; }
private StandardType1Font _FonteRegular;
private StandardType1Font _FonteNegrito;
private StandardType1Font _FonteItalico;
private StandardType1Font.FamilyEnum _FonteFamilia;
private Boolean _FoiGerado;
private org.pdfclown.documents.contents.xObjects.XObject _LogoObject = null;
public Danfe(DanfeViewModel viewModel)
{
ViewModel = viewModel ?? throw new ArgumentNullException(nameof(viewModel));
_Blocos = new List<BlocoBase>();
File = new File();
PdfDocument = File.Document;
// De acordo com o item 7.7, a fonte deve ser Times New Roman ou Courier New.
_FonteFamilia = StandardType1Font.FamilyEnum.Times;
_FonteRegular = new StandardType1Font(PdfDocument, _FonteFamilia, false, false);
_FonteNegrito = new StandardType1Font(PdfDocument, _FonteFamilia, true, false);
_FonteItalico = new StandardType1Font(PdfDocument, _FonteFamilia, false, true);
EstiloPadrao = CriarEstilo();
Paginas = new List<DanfePagina>();
Canhoto = CriarBloco<BlocoCanhoto>();
IdentificacaoEmitente = AdicionarBloco<BlocoIdentificacaoEmitente>();
AdicionarBloco<BlocoDestinatarioRemetente>();
if (ViewModel.LocalRetirada != null && ViewModel.ExibirBlocoLocalRetirada)
AdicionarBloco<BlocoLocalRetirada>();
if (ViewModel.LocalEntrega != null && ViewModel.ExibirBlocoLocalEntrega)
AdicionarBloco<BlocoLocalEntrega>();
if (ViewModel.Duplicatas.Count > 0)
AdicionarBloco<BlocoDuplicataFatura>();
AdicionarBloco<BlocoCalculoImposto>(ViewModel.Orientacao == Orientacao.Paisagem ? EstiloPadrao : CriarEstilo(4.75F));
AdicionarBloco<BlocoTransportador>();
AdicionarBloco<BlocoDadosAdicionais>(CriarEstilo(tFonteCampoConteudo: 8));
if(ViewModel.CalculoIssqn.Mostrar)
AdicionarBloco<BlocoCalculoIssqn>();
AdicionarMetadata();
_FoiGerado = false;
}
public void AdicionarLogoImagem(System.IO.Stream stream)
{
if (stream == null) throw new ArgumentNullException(nameof(stream));
var img = org.pdfclown.documents.contents.entities.Image.Get(stream);
if (img == null) throw new InvalidOperationException("O logotipo não pode ser carregado, certifique-se que a imagem esteja no formato JPEG não progressivo.");
_LogoObject = img.ToXObject(PdfDocument);
}
public void AdicionarLogoPdf(System.IO.Stream stream)
{
if (stream == null) throw new ArgumentNullException(nameof(stream));
using (var pdfFile = new org.pdfclown.files.File(new org.pdfclown.bytes.Stream(stream)))
{
_LogoObject = pdfFile.Document.Pages[0].ToXObject(PdfDocument);
}
}
public void AdicionarLogoImagem(String path)
{
if (String.IsNullOrWhiteSpace(path)) throw new ArgumentException(nameof(path));
using(var fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
AdicionarLogoImagem(fs);
}
}
public void AdicionarLogoPdf(String path)
{
if (String.IsNullOrWhiteSpace(path)) throw new ArgumentException(nameof(path));
using (var fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
AdicionarLogoPdf(fs);
}
}
private void AdicionarMetadata()
{
var info = PdfDocument.Information;
info[new org.pdfclown.objects.PdfName("ChaveAcesso")] = ViewModel.ChaveAcesso;
info[new org.pdfclown.objects.PdfName("TipoDocumento")] = "DANFE";
info.CreationDate = DateTime.Now;
info.Creator = String.Format("{0} {1} - {2}", "DanfePDF", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version, "https://github.com/SilverCard/DanfePDF");
info.Title = "DANFE (Documento auxiliar da NFe)";
}
private Estilo CriarEstilo(float tFonteCampoCabecalho = 6, float tFonteCampoConteudo = 10)
{
return new Estilo(_FonteRegular, _FonteNegrito, _FonteItalico, tFonteCampoCabecalho, tFonteCampoConteudo);
}
public void Gerar()
{
if (_FoiGerado) throw new InvalidOperationException("O Danfe já foi gerado.");
IdentificacaoEmitente.Logo = _LogoObject;
var tabela = new TabelaProdutosServicos(ViewModel, EstiloPadrao);
while (true)
{
DanfePagina p = CriarPagina();
tabela.SetPosition(p.RetanguloCorpo.Location);
tabela.SetSize(p.RetanguloCorpo.Size);
tabela.Draw(p.Gfx);
p.Gfx.Stroke();
p.Gfx.Flush();
if (tabela.CompletamenteDesenhada) break;
}
PreencherNumeroFolhas();
_FoiGerado = true;
}
private DanfePagina CriarPagina()
{
DanfePagina p = new DanfePagina(this);
Paginas.Add(p);
p.DesenharBlocos(Paginas.Count == 1);
p.DesenharCreditos();
// Ambiente de homologação
// 7. O DANFE emitido para representar NF-e cujo uso foi autorizado em ambiente de
// homologação sempre deverá conter a frase “SEM VALOR FISCAL” no quadro “Informações
// Complementares” ou em marca d’água destacada.
if (ViewModel.TipoAmbiente == 2)
p.DesenharAvisoHomologacao();
return p;
}
internal T CriarBloco<T>() where T : BlocoBase
{
return (T)Activator.CreateInstance(typeof(T), ViewModel, EstiloPadrao);
}
internal T CriarBloco<T>(Estilo estilo) where T : BlocoBase
{
return (T)Activator.CreateInstance(typeof(T), ViewModel, estilo);
}
internal T AdicionarBloco<T>() where T: BlocoBase
{
var bloco = CriarBloco<T>();
_Blocos.Add(bloco);
return bloco;
}
internal T AdicionarBloco<T>(Estilo estilo) where T : BlocoBase
{
var bloco = CriarBloco<T>(estilo);
_Blocos.Add(bloco);
return bloco;
}
internal void AdicionarBloco(BlocoBase bloco)
{
_Blocos.Add(bloco);
}
internal void PreencherNumeroFolhas()
{
int nFolhas = Paginas.Count;
for (int i = 0; i < Paginas.Count; i++)
{
Paginas[i].DesenhaNumeroPaginas(i + 1, nFolhas);
}
}
public void Salvar(String path)
{
if (String.IsNullOrWhiteSpace(path)) throw new ArgumentException(nameof(path));
File.Save(path, SerializationModeEnum.Incremental);
}
public void Salvar(System.IO.Stream stream)
{
if (stream == null) throw new ArgumentNullException(nameof(stream));
File.Save(new org.pdfclown.bytes.Stream(stream), SerializationModeEnum.Incremental);
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
File.Dispose();
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~Danfe() {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
}
}