Текущая функциональность системы: система собирает несколько счетов-фактур в формате PDF для каждого клиента, объединяет все эти счета-фактуры в один счет-фактуру в формате PDF и отправляет одно электронное письмо клиенту. Если у клиента было 10 счетов в месяц, система объединит все эти счета в один файл PDF и отправит его клиенту. PDF будет использовать одно имя счета. Это происходит со всеми клиентами.
Запрошенные изменения: некоторые из них больше не хотят, чтобы их счет был объединен в один PDF-файл. Они хотят, чтобы каждый счет отправлялся отдельно. Это будет основано на клиенте, так как некоторые из клиентов продолжат работу с существующей функциональностью. AccountId - это первичный ключ, который я буду использовать, чтобы исключить слияние счетов. Если AccountId не найден, что означает, что он будет объединен, то стих Visa. Имя счета должно быть уникальным (AccountName_1). он будет увеличивать 1 или помещать идентификатор GuidID каждый раз.
Моя проблема: создается пустой счет-фактура, создается впечатление, будто я создаю новый экземпляр существующего PDF-файла и, следовательно, он стал пустым. Я добавил текст в абзац, и он будет писать этот текст, но не фактические данные счета. Я не уверен, как / где данные счета были добавлены. Пожалуйста, помогите и извините за эссе.
Существующий код функциональности.
Метод 1:
public MessageQueue CollateDocumentsForMessage(MessageQueue message, MessageSchedulerSettings settings, CompanySegmentSettings currentCompanySegmentsSetings)
{
---
---Some existing codes for checks
---
//Retrieve documents
var resultCollection = new ConcurrentBag<FinancialDocument>();
ParallelLoopResult loopResults = Parallel.ForEach(documents, d =>
{
try
{
d.Document = RetrieveDocument(d.DocumentUrl);
resultCollection.Add(d);
}
catch (Exception ex)
{
logger.Error(ex, "Failed to download DocumentNumber: {0}", d.MetaData.DocumentNumber);
throw;
}
});
if (!loopResults.IsCompleted)
{
message.Status = MessageQueueStatus.Error;
message.ErrorName = "DocumentGeneratorError";
message.ErrorDescription = string.Format("Failed to download one of the documents for message {0}", message.Id);
}
var reorderedFinDocs = resultCollection.OrderBy(a => a.MetaData.DocumentDate).ThenBy(a => a.MetaData.DocumentNumber);
var currentOutputDirectory = generatedPDFsDirectory(settings.DocumentOutputDirectory);
var outputFileName = $"{currentCompanySegmentsSetings.FriendlySegmentName}-{Translator.TranslateDocumentType("invoice", currentCompanySegmentsSetings).ToLower()}-{message.documents.First().AccountNumber}.pdf";
string documentPath = documentProvider.MergeAndSaveDocument(message, reorderedFinDocs, coverPageTemplateLocation, currentOutputDirectory, outputFileName, currentCompanySegmentsSetings);
message.FinancialDocumentAttachments.Add(new MessageQueueAttachment()
{
Location = documentPath,
IsNew = true,
Id = Guid.NewGuid()
});
}
}
return message;
}
Метод 2:
public string MergeAndSaveDocument(MessageQueue message, IEnumerable<FinancialDocument> financialDocument, string coverPageTemplate, string outputDirectory, string outputFilename, CompanySegmentSettings currentCompanySegmentsSetings)
{
System.IO.Directory.CreateDirectory(outputDirectory);
var firstDocsMetadata = financialDocument.First().MetaData;
string generatedPDFLocation = System.IO.Path.Combine(outputDirectory, outputFilename);
var filesToMerge = FinancialDocumentsToPDFDocs(financialDocument);
//Creates new pdf
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(generatedPDFLocation, CreateEncryptionWriteProperties()));
Document doc = new Document(pdfDoc);
//Bookmarks
pdfDoc.GetCatalog().SetPageMode(PdfName.UseOutlines);
doc.SetMargins(22f, 22f, 22f, 22f);
doc.SetFontSize(8);
doc.SetFontColor(Color.BLACK);
//2. Merge financial documents
mergeDocumentsAndAddBooks(doc, filesToMerge);
//3. Close documents
doc.Close();
foreach (PdfDocument srcDoc in filesToMerge.Values)
{
srcDoc.Close();
}
doc.Close();
return System.IO.Path.GetFullPath(generatedPDFLocation);
}
Метод 3: Этот метод объединяет все счета
private void mergeDocumentsAndAddBooks(Document targetDocument, Dictionary<FinancialDocument, PdfDocument> filesToMerge)
{
int n;
PdfDocument pdfDoc = targetDocument.GetPdfDocument();
int pageNo = pdfDoc.GetNumberOfPages();
//Create bookmarks
PdfOutline docOutline = pdfDoc.GetOutlines(false);
foreach (var entry in filesToMerge)
{
PdfOutline outline = docOutline.AddOutline(string.Format("{0}-Page 1 of 1", entry.Key.MetaData.DocumentNumber.ToString()));
string destinationText = "p" + entry.Key.MetaData.DocumentNumber;
outline.AddDestination(PdfDestination.MakeDestination(new PdfString(destinationText)));
n = entry.Value.GetNumberOfPages();
for (int i = 1; i <= n; i++)
{
pageNo++;
Text text = new Text("");
entry.Value.CopyPagesTo(i, i, pdfDoc);
if (i == 1)
{
text.SetDestination(entry.Key.MetaData.DocumentNumber);
}
targetDocument.Add(new Paragraph(text).SetFixedPosition(pageNo, 549, 870, 40));
}
}
}
То, что я пробовал: я пытался внести некоторые изменения в Метод 1. Я не уверен, что это правильное место для этого или что.
public MessageQueue CollateDocumentsForMessage(MessageQueue message, MessageSchedulerSettings settings, CompanySegmentSettings currentCompanySegmentsSetings)
{
--
--Some checks
--
var reorderedFinDocs = resultCollection.OrderBy(a => a.MetaData.DocumentDate).ThenBy(a => a.MetaData.DocumentNumber);
var currentOutputDirectory = generatedPDFsDirectory(settings.DocumentOutputDirectory);
#region Excluded accounts for invoice merging
//Accounts for separate invoices
//<add key="AccountNumbers" value="account1,account2,account3,account4" />
string[] accountArray = System.Configuration.ConfigurationManager.AppSettings["AccountNumbers"].Split(',').Select(s => s.Trim()).ToArray();
List<string> accountlist = new List<string>(accountArray);
foreach (var item in documents)
{
if (accountlist.Contains(item.MetaData.AccountNumber))
{
var guidID = Guid.NewGuid().ToString();
var newFileName = $"{currentCompanySegmentsSetings.FriendlySegmentName}-{Translator.TranslateDocumentType("invoice", currentCompanySegmentsSetings).ToLower()}-{guidID}-{message.documents.First().AccountNumber}.pdf";
outputFileNames.Add(newFileName);
System.IO.Directory.CreateDirectory(currentOutputDirectory);
var firstDocsMetadata = documents.First().MetaData;
string generatedPDFLocation = System.IO.Path.Combine(currentOutputDirectory, newFileName);
var files = FinancialDocsToPDFDocs(documents);
//Creates new pdf
FinDoc.DocumemtProvider.PDFDocumentProvider.PDFDocumentProvider docProvider = new PDFDocumentProvider();
var encription = docProvider.CreateEncryptionWriteProperties();
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(generatedPDFLocation, encription));
//Document doc = new Document(files.First().Value);
Document doc = new Document(pdfDoc);
//Bookmarks
pdfDoc.GetCatalog().SetPageMode(PdfName.UseOutlines);
doc.SetMargins(22f, 22f, 22f, 22f);
doc.SetFontSize(8);
doc.SetFontColor(Color.BLACK);
PdfOutline docOutline = pdfDoc.GetOutlines(false);
PdfOutline outline = docOutline.AddOutline(string.Format("{0}-Page 1 of 1", item.MetaData.DocumentNumber.ToString()));
string destinationText = "p" + item.MetaData.DocumentNumber;
outline.AddDestination(PdfDestination.MakeDestination(new PdfString(destinationText)));
doc.Add(new Paragraph("Example"));
doc.Close();
string filePath = @"C:\xxxx\xxxxx\";
string absolutePath = Path.GetFullPath(filePath + currentOutputDirectory + newFileName);
//string absolutePath = documentProvider.NoMergeDocumentsAndAddBooks(message, reorderedFinDocs, coverPageTemplateLocation, currentOutputDirectory, newFileName, currentCompanySegmentsSetings);
message.FinancialDocumentAttachments.Add(new MessageQueueAttachment()
{
Location = absolutePath,
IsNew = true,
Id = Guid.NewGuid()
});
}
else
{
var outputFileName = $"{currentCompanySegmentsSetings.FriendlySegmentName}-{Translator.TranslateDocumentType("invoice", currentCompanySegmentsSetings).ToLower()}-{message.documents.First().AccountNumber}.pdf";
string documentPath = documentProvider.MergeAndSaveDocument(message, reorderedFinDocs, coverPageTemplateLocation, currentOutputDirectory, outputFileName, currentCompanySegmentsSetings);
message.FinancialDocumentAttachments.Add(new MessageQueueAttachment()
{
Location = documentPath,
IsNew = true,
Id = Guid.NewGuid()
});
}
}
#endregion
return message;
}