@asad.ali
I changed the code to follow your recommendation and we are just passing the single page into the methods now and it is still coming at as follows with the header and footer duplicated.
Packet_20231130202820244.pdf (555.7 KB)
for (int i = 1; i <= tempCompiledDoc.Pages.Count; i++)
{
bc.ThrowIfTaskCancelled(bc.CancellationToken);
if (badPages.Contains(i))
{
if (!string.IsNullOrWhiteSpace(pageHeaders[i - 1]))
{
var stampValue = pageHeaders[i - 1]
.Replace("{{document.pagecount}}", (bc.AzureQueueCompileModel.TotalDocumentPageCount + tempCompiledDoc.Pages.Count).ToString())
.Replace("{{document.pagenumber}}", (i).ToString())
.Replace("{{document.pagecountafteragenda}}", bc.AzureQueueCompileModel.TotalDocumentPageCount.ToString())
.Replace("{{document.pagenumberafteragenda}}", (i == totalAgendaPageCount ? i.ToString() : ""));
AddHeaderStamp(tempCompiledDoc.Pages[i], stampValue, true);
}
if (!string.IsNullOrWhiteSpace(pageFooters[i]))
{
var stampValue = pageFooters[i - 1]
.Replace("{{document.pagecount}}", (bc.AzureQueueCompileModel.TotalDocumentPageCount + tempCompiledDoc.Pages.Count).ToString())
.Replace("{{document.pagenumber}}", (i).ToString())
.Replace("{{document.pagecountafteragenda}}", bc.AzureQueueCompileModel.TotalDocumentPageCount.ToString())
.Replace("{{document.pagenumberafteragenda}}", (i == totalAgendaPageCount ? i.ToString() : ""));
AddFooterStamp(tempCompiledDoc.Pages[i], stampValue, true);
}
}
else
{
if (!string.IsNullOrWhiteSpace(pageHeaders[i - 1]))
{
var stampValue = pageHeaders[i - 1]
.Replace("{{document.pagecount}}", tempCompiledDoc.Pages.Count.ToString())
.Replace("{{document.pagenumber}}", (i).ToString())
.Replace("{{document.pagecountafteragenda}}", bc.AzureQueueCompileModel.TotalDocumentPageCount.ToString())
.Replace("{{document.pagenumberafteragenda}}", (i > totalAgendaPageCount ? i.ToString() : ""));
AddHeaderStamp(tempCompiledDoc.Pages[i], stampValue);
}
if (!string.IsNullOrWhiteSpace(pageFooters[i - 1]))
{
var stampValue = pageFooters[i - 1]
.Replace("{{document.pagecount}}", tempCompiledDoc.Pages.Count.ToString())
.Replace("{{document.pagenumber}}", (i).ToString())
.Replace("{{document.pagecountafteragenda}}", bc.AzureQueueCompileModel.TotalDocumentPageCount.ToString())
.Replace("{{document.pagenumberafteragenda}}", (i > totalAgendaPageCount ? i.ToString() : ""));
AddFooterStamp(tempCompiledDoc.Pages[i], stampValue);
}
}
}
which calls the following 1 of the following
public void AddFooterStamp(Aspose.Pdf.Page page, string value, bool isBadPage = false)
{
AddFooter(page, value, isBadPage);
}
public void AddHeaderStamp(Aspose.Pdf.Page page, string value, bool isBadPage = false)
{
AddHeader(page, value, isBadPage);
}
private void AddFooter(Aspose.Pdf.Page page, string value, bool isBadPage = false)
{
if (isBadPage)
{
Aspose.Pdf.Text.Font headerFooterFont = FontRepository.FindFont("Times New Roman");
float headerFooterFontSize = 10;
double headerFooterMarginLeft = 90;
Aspose.Pdf.VerticalAlignment footerVerticalAlignment = Aspose.Pdf.VerticalAlignment.Bottom;
Aspose.Pdf.HorizontalAlignment headerFooterHorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Right;
AddStamp(page, value, footerVerticalAlignment, headerFooterHorizontalAlignment, headerFooterFont, headerFooterFontSize, headerFooterMarginLeft);
}
else
{
page.Footer = new Aspose.Pdf.HeaderFooter();
if (CustomerConfig.For(bc.CustomerCallContext).PdfMarginRight != null)
page.Footer.Margin.Right = int.Parse(CustomerConfig.For(bc.CustomerCallContext).PdfMarginRight);
else
page.Footer.Margin.Right = 50;
if (CustomerConfig.For(bc.CustomerCallContext).PdfMarginLeft != null)
page.Footer.Margin.Left = int.Parse(CustomerConfig.For(bc.CustomerCallContext).PdfMarginLeft);
else
page.Footer.Margin.Left = 50;
page.Footer.Paragraphs.Add(new Aspose.Pdf.HtmlFragment(value));
}
}
private void AddHeader(Aspose.Pdf.Page page, string value, bool isBadPage = false)
{
if (isBadPage)
{
Aspose.Pdf.Text.Font headerFooterFont = FontRepository.FindFont("Times New Roman");
float headerFooterFontSize = 10;
double headerFooterMarginLeft = 90;
Aspose.Pdf.HorizontalAlignment headerFooterHorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Right;
Aspose.Pdf.VerticalAlignment headerVerticalAlignment = Aspose.Pdf.VerticalAlignment.Top;
AddStamp(page, value, headerVerticalAlignment, headerFooterHorizontalAlignment, headerFooterFont, headerFooterFontSize, headerFooterMarginLeft);
}
else
{
//var page = compiledDoc.Pages[pageIndex];
page.Header = new Aspose.Pdf.HeaderFooter();
if (CustomerConfig.For(bc.CustomerCallContext).PdfMarginRight != null)
page.Header.Margin.Right = int.Parse(CustomerConfig.For(bc.CustomerCallContext).PdfMarginRight);
else
page.Header.Margin.Right = 50;
if (CustomerConfig.For(bc.CustomerCallContext).PdfMarginLeft != null)
page.Header.Margin.Left = int.Parse(CustomerConfig.For(bc.CustomerCallContext).PdfMarginLeft);
else
page.Header.Margin.Left = 50;
page.Header.Paragraphs.Add(new Aspose.Pdf.HtmlFragment(value));
}
}
private void AddStamp(Aspose.Pdf.Page page, string value, Aspose.Pdf.VerticalAlignment verticalAlignment, Aspose.Pdf.HorizontalAlignment horizontalAlignment, Aspose.Pdf.Text.Font headerFooterFont, float headerFooterFontSize, double headerFooterMarginLeft)
{
var formattedValue = System.Text.RegularExpressions.Regex.Replace(value, "<.*?>", string.Empty);
FormattedText text = new FormattedText();
foreach (var item in formattedValue.Split('\n').Where(x => !string.IsNullOrEmpty(x.Trim())))
{
text.AddNewLineText(item + "\t\t\t\t\t\t\t\t\t\t\t\t");
}
text.AddNewLineText(Environment.NewLine);
var ts = new Aspose.Pdf.TextStamp(text)
{
TopMargin = 10,
WordWrap = true,
Scale = false,
Width = page.PageInfo.Width,
VerticalAlignment = verticalAlignment,
HorizontalAlignment = horizontalAlignment,
LeftMargin = page.PageInfo.Width - headerFooterMarginLeft
};
ts.TextState.Font = headerFooterFont;
ts.TextState.FontSize = headerFooterFontSize;
page.AddStamp(ts);
}
You will notice I am not passing in the page each time instead of the entire document. It is duplicating the footer and the header each time regardless.
I don’t know if it is important to mention again but this PDF is being generated by a docx that is being coverted to PDF using aspose. Is there a setting when adding the headers/footers that tells the system to have each page the same?
I also noticed in your code you are creating a PDF using aspose Document.
Here is our entire code that generates the PDF and you will notice is is an already existing DOCX
public async Task ShouldCreatePDFFromDocxCompile(string permFilePath, CompileMeetingContentModel data, CompiledMeetingDocument compiledMeetingDoc = null)
{
if (bc.AutoCreatePdfFromDocxSetting != true)
{
return;
}
DateTime? created = DateTime.UtcNow;
if (data == null)
{
data = await bc.GetMeetingData(compiledMeetingDoc);
await bc.CompileUpdates.SendCompileUpdates(
bc.AzureQueueCompileModel,
CompileEvents.Updated,
new int[1] { 1 },
null
);
}
var compiledDoc = await bc.StartCompile(data.Meeting.Id, data.MeetingTemplate.Id, new List<CompileOutputTypes>() { CompileOutputTypes.Pdf }, created);
compiledDoc.MeetingTemplateId = data.MeetingTemplate?.Id ?? null;
var file = compiledDoc.CompiledMeetingDocumentFiles.FirstOrDefault(x => x.CompileOutputType == CompileOutputTypes.Pdf);
file.PublishStatus = PublishStatuses.Unpublish;
file.Language = Localizer_i18n.CurrentLanguage.Value;
Aspose.Words.Saving.PdfSaveOptions pdfSaveOptions = new Aspose.Words.Saving.PdfSaveOptions();
pdfSaveOptions.Compliance = Aspose.Words.Saving.PdfCompliance.PdfA2a;
string fileName = string.Format("{0}_{1}", HelperLogic.CleanFilename(data.MeetingTemplate.Name), compiledDoc.Created.ToString("yyyyMMddHHmmssFFF"));
var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "temp", $"{data.Meeting.Id}", $"{fileName}.pdf");
var docxDocument = new Document(bc.AzureProvider.DownloadToStream(permFilePath));
ELSLogHelper.InsertInfoLog(ELSLogHelper.AsposeLogMessage("Load"), MethodBase.GetCurrentMethod()?.Name, MethodBase.GetCurrentMethod().DeclaringType?.Name, Environment.StackTrace);
docxDocument.Save(filePath, pdfSaveOptions);
ELSLogHelper.InsertInfoLog(ELSLogHelper.AsposeLogMessage("Save"), MethodBase.GetCurrentMethod()?.Name, MethodBase.GetCurrentMethod().DeclaringType?.Name, Environment.StackTrace);
bool meetingTemplateIncludeDocuments = data.MeetingTemplate.IncludeSystemDocuments || data.MeetingTemplate.IncludeAttachments;
bool compileServiceIsAvailable = await bc.BaseSettings.GetCompileServiceFeatureFlag();
bool compileOutputTypeIsPdf = file.CompileOutputType == CompileOutputTypes.Pdf;
List<int> badPages = new List<int>();
var pageHeaders = new List<string>();
var pageFooters = new List<string>();
if (meetingTemplateIncludeDocuments)
{
var meetingTitle = data.Meeting.Title;
Aspose.Pdf.Document tempCompiledDoc;
using (var pdfStream = File.Open(filePath, FileMode.Open))
{
tempCompiledDoc = new Aspose.Pdf.Document(pdfStream);
}
var totalAgendaPageCount = tempCompiledDoc.Pages.Count;
var agHeaderFormat = data.MeetingTypeTemplate.CompileAgendaPageHeader;
var agFooterFormat = data.MeetingTypeTemplate.CompileAgendaPageFooter;
string location = data.Meeting.Location;
List<string> nextMeeting = await bc.MeetingLogic.NextbyDatetime(data.Meeting.Id, data.Meeting.MeetingTypeId, data.Meeting.ScheduledEvent.Start);
var templateName = data.MeetingTypeTemplate.Name;
var nextDate = "";
var nextTime = "";
var nextLocation = "";
string itemTitle = data.MeetingTypeTemplate.Name;
if (nextMeeting != null && nextMeeting.Count > 0)
{
nextDate = nextMeeting[0];
nextTime = nextMeeting[1];
nextLocation = nextMeeting[2];
}
//This is for page headers and footers on the Agenda only.
for (int i = 0; i < tempCompiledDoc.Pages.Count; i++)
{
bc.ThrowIfTaskCancelled(bc.CancellationToken);
var headerFormatValue = new HeaderFooterFormatValue(agHeaderFormat, meetingTitle, itemTitle, nextDate, nextTime, location, nextLocation)
{
AgendaPageNumber = (i + 1).ToString(),
AgendaPageCount = tempCompiledDoc.Pages.Count.ToString(),
TemplateName = templateName,
MeetingDatetime = DateTimeLogic.GetLocalTime(bc.CustomerCallContext.TimeZone, data.Meeting.ScheduledEvent.Start).ToString(),
MeetingLocation = location,
CompileDatetime = DateTimeLogic.GetLocalTime(bc.CustomerCallContext.TimeZone, Convert.ToDateTime(created)).ToString(),
MeetingCustomTrackingNumber = data.Meeting.CustomTrackingNumber,
Committee = data.Meeting.MeetingType.Committee.Name,
NextDate = nextDate,
NextTime = nextTime,
NextLocation = nextLocation
};
pageHeaders.Add(bc.ReplaceHeaderFooterFormatValues(headerFormatValue));
var footerFormatValue = new HeaderFooterFormatValue(agFooterFormat, meetingTitle, itemTitle, nextDate, nextTime, location, nextLocation)
{
AgendaPageNumber = (i + 1).ToString(),
AgendaPageCount = tempCompiledDoc.Pages.Count.ToString(),
TemplateName = templateName,
MeetingDatetime = DateTimeLogic.GetLocalTime(bc.CustomerCallContext.TimeZone, data.Meeting.ScheduledEvent.Start).ToString(),
MeetingLocation = location,
CompileDatetime = DateTimeLogic.GetLocalTime(bc.CustomerCallContext.TimeZone, Convert.ToDateTime(created)).ToString(),
MeetingCustomTrackingNumber = data.Meeting.CustomTrackingNumber,
Committee = data.Meeting.MeetingType.Committee.Name,
NextDate = nextDate,
NextTime = nextTime,
NextLocation = nextLocation
};
pageFooters.Add(bc.ReplaceHeaderFooterFormatValues(footerFormatValue));
}
await IncludeAttachmentsUsingAspose(data, tempCompiledDoc, pageHeaders, pageFooters, meetingTitle, Convert.ToDateTime(created), badPages);
for (int i = 1; i <= tempCompiledDoc.Pages.Count; i++)
{
bc.ThrowIfTaskCancelled(bc.CancellationToken);
if (badPages.Contains(i))
{
if (!string.IsNullOrWhiteSpace(pageHeaders[i - 1]))
{
var stampValue = pageHeaders[i - 1]
.Replace("{{document.pagecount}}", (bc.AzureQueueCompileModel.TotalDocumentPageCount + tempCompiledDoc.Pages.Count).ToString())
.Replace("{{document.pagenumber}}", (i).ToString())
.Replace("{{document.pagecountafteragenda}}", bc.AzureQueueCompileModel.TotalDocumentPageCount.ToString())
.Replace("{{document.pagenumberafteragenda}}", (i == totalAgendaPageCount ? i.ToString() : ""));
AddHeaderStamp(tempCompiledDoc.Pages[i], stampValue, true);
}
if (!string.IsNullOrWhiteSpace(pageFooters[i]))
{
var stampValue = pageFooters[i - 1]
.Replace("{{document.pagecount}}", (bc.AzureQueueCompileModel.TotalDocumentPageCount + tempCompiledDoc.Pages.Count).ToString())
.Replace("{{document.pagenumber}}", (i).ToString())
.Replace("{{document.pagecountafteragenda}}", bc.AzureQueueCompileModel.TotalDocumentPageCount.ToString())
.Replace("{{document.pagenumberafteragenda}}", (i == totalAgendaPageCount ? i.ToString() : ""));
AddFooterStamp(tempCompiledDoc.Pages[i], stampValue, true);
}
}
else
{
if (!string.IsNullOrWhiteSpace(pageHeaders[i - 1]))
{
var stampValue = pageHeaders[i - 1]
.Replace("{{document.pagecount}}", tempCompiledDoc.Pages.Count.ToString())
.Replace("{{document.pagenumber}}", (i).ToString())
.Replace("{{document.pagecountafteragenda}}", bc.AzureQueueCompileModel.TotalDocumentPageCount.ToString())
.Replace("{{document.pagenumberafteragenda}}", (i > totalAgendaPageCount ? i.ToString() : ""));
AddHeaderStamp(tempCompiledDoc.Pages[i], stampValue);
}
if (!string.IsNullOrWhiteSpace(pageFooters[i - 1]))
{
var stampValue = pageFooters[i - 1]
.Replace("{{document.pagecount}}", tempCompiledDoc.Pages.Count.ToString())
.Replace("{{document.pagenumber}}", (i).ToString())
.Replace("{{document.pagecountafteragenda}}", bc.AzureQueueCompileModel.TotalDocumentPageCount.ToString())
.Replace("{{document.pagenumberafteragenda}}", (i > totalAgendaPageCount ? i.ToString() : ""));
AddFooterStamp(tempCompiledDoc.Pages[i], stampValue);
}
}
}
await SavePdfFile(file, fileName, data.Meeting.Id, false, tempCompiledDoc);
tempCompiledDoc.FreeMemory();
tempCompiledDoc.Dispose();
tempCompiledDoc = null;
}
else
{
file.FilePath = string.Format("Meetings/{0}/{1}{2}", data.Meeting.Id, fileName, ".pdf");
file.CompileFinishedDate = DateTime.UtcNow;
await bc.AzureProvider.SaveAzureFileAsync(file.FilePath, File.ReadAllBytes(filePath));
}
await bc.CustomerCallContext.SystemContext.UpdateFileAsync(file);
if (File.Exists(filePath))
{
File.Delete(filePath);
}
docxDocument = null;
bc.ThrowIfTaskCancelled(bc.CancellationToken);
await bc.SaveCompile(compiledDoc);
GC.Collect();
}