We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Insert Header/Footer from another document

Hello,

I have a document (A) without headers and footer and a document B with headers/ footers / images

I would like to add the header/footers/images from document B into document A and save document A as pdf.

I can’t find the solution.
Thanks for a quick response.

re Bert

Hi Bert,


Thanks for your inquiry. You can achieve this using Aspose.Words. You can try using the following code:
//Open A document
Document docA = new Document(getMyDir() + “a.docx”);
DocumentBuilder builderA = new DocumentBuilder(docA);
//Open B document
Document docB = new Document(getMyDir() + “b.docx”);
//Loop through all sections in the B document
for (Section sectB : (Iterable<Section>) docB.getSections())
{
Section sectA = null;
int sectBIndex = docB.getSections().indexOf(sectB);
//Check whether document A conteins section with same index
if (docA.getSections().getCount() > sectBIndex)
{
//Get correcponding section
sectA = docA.getSections().get(sectBIndex);
}
else
{
//Insert empty section
builderA.moveToDocumentEnd();
builderA.insertBreak(BreakType.SECTION_BREAK_CONTINUOUS);
sectA = builderA.getCurrentSection();
}
//Loop throught all Headers/Footers in the B document
for (HeaderFooter hfB : sectB.getHeadersFooters())
{
//Check whether current section from docA conteins
//Header/Footer with the same type as h/f from docB
if (sectA.getHeadersFooters().getByHeaderFooterType(hfB.getHeaderFooterType()) != null)
{
//Append content from h/f B to h/f A
for (Node childB : (Iterable<Node>) hfB.getChildNodes())
{
//Import node
Node childA = docA.importNode(childB, true, ImportFormatMode.KEEP_SOURCE_FORMATTING);
//Appent node to h/f
sectA.getHeadersFooters().getByHeaderFooterType(hfB.getHeaderFooterType()).appendChild(childA);
}
}
else
{
//Copy whole h/f
Node hfA = docA.importNode(hfB, true, ImportFormatMode.KEEP_SOURCE_FORMATTING);
//Insert h/f
sectA.getHeadersFooters().add(hfA);
}
}
}

//Save output document
docA.save(getMyDir() + “out.docx”);

I hope, this helps.

Best regards,

I had this already in my code. However if the margins are in the original document not exactly the same as the document which has the background it will not merge correct.

So I need something which is more robust.
I was looking for something that I can position the text blocks from the top of the paper. However if I try this in Word it will not do that

So any other thoughts.

Hi Bert,

Thanks for your inquiry. You can set values of left, top, right and bottom margins of the second Document to the values found in original document using Section.PageSetup. Also, please see PageSetup.HeaderDistance and PageSetup.FooterDistance properties. I hope, this helps.

Best regards,