OpenXML Пейзаж на определенных разделах
Как вы устанавливаете определенные разделы (какие типы разделов я должен использовать?) В альбомную или портретную ориентацию?
Я пытаюсь создать разделы, которые имеют следующие свойства раздела (см. Код ниже), а затем установить для этого раздела соответственно альбомную или книжную ориентацию. Однако, когда я использую этот код и создаю параграфы разрыва, код генерирует пустую страницу в альбомной ориентации.
public static SectionProperties PageOrientationPortrait()
{
SectionProperties sectionProperties2 = new SectionProperties();
PageSize pageSize = new PageSize()
{
Width = (UInt32Value)12240U,
Height = (UInt32Value)15840U,
Orient = PageOrientationValues.Portrait
};
PageMargin pageMargin = new PageMargin()
{
Top = 1440,
Right = (UInt32Value)1440U,
Bottom = 1440,
Left = (UInt32Value)1440U,
Header = (UInt32Value)720U,
Footer = (UInt32Value)720U,
Gutter = (UInt32Value)0U
};
Columns columns = new Columns() { Space = "720" };
DocGrid docGrid = new DocGrid() { LinePitch = 360 };
sectionProperties2.Append(pageSize, pageMargin, columns, docGrid);
return sectionProperties2;
}
public static SectionProperties PageOrientationLandScape()
{
SectionProperties sectionProperties = new SectionProperties();
PageSize pageSize = new PageSize()
{
Width = (UInt32Value)15840U,
Height = (UInt32Value)12240U,
Orient = PageOrientationValues.Landscape
};
PageMargin pageMargin = new PageMargin()
{
Top = 1440,
Right = (UInt32Value)1440U,
Bottom = 1440,
Left = (UInt32Value)1440U,
Header = (UInt32Value)720U,
Footer = (UInt32Value)720U,
Gutter = (UInt32Value)0U
};
Columns columns = new Columns() { Space = "720" };
DocGrid docGrid = new DocGrid() { LinePitch = 360 };
sectionProperties.Append(pageSize, pageMargin, columns, docGrid);
return sectionProperties;
}
public static Paragraph GenerateSectionBreakParagraph()
{
Paragraph paragraph232 = new Paragraph();
ParagraphProperties paragraphProperties220 = new ParagraphProperties();
SectionProperties sectionProperties1 = new SectionProperties();
SectionType sectionType1 = new SectionType() { Val = SectionMarkValues.NextPage };
sectionProperties1.Append(sectionType1);
paragraphProperties220.Append(sectionProperties1);
paragraph232.Append(paragraphProperties220);
return paragraph232;
}
0 ответов
Если вы хотите создать стандартный раздел в документе WordProcessing, вам сначала необходимо создать пустой элемент Paragraph и пустой элемент ParagraphProperties. Затем вы можете создать элемент SectionProperties с желаемыми свойствами, как показано ниже:
/// <summary>
/// Will create a section properties
/// </summary>
/// <param name="orientation">The wanted orientation (landscape or portrai)</param>
/// <returns>A section properties element</returns>
public static SectionProperties CreateSectionProperties(PageOrientationValues orientation)
{
// create the section properties
SectionProperties properties = new SectionProperties();
// create the height and width
UInt32Value height = orientation == (PageOrientationValues.Portrait) ? 16839U : 11907U;
UInt32Value width = orientation != (PageOrientationValues.Portrait) ? 16839U : 11907U;
// create the page size and insert the wanted orientation
PageSize pageSize = new PageSize()
{
Width = width,
Height = height,
Code = (UInt16Value)9U,
// insert the orientation
Orient = orientation };
// create the page margin
PageMargin pageMargin = new PageMargin()
{
Top = 1417,
Right = (UInt32Value)1417U,
Bottom = 1417,
Left = (UInt32Value)1417U,
Header = (UInt32Value)708U,
Footer = (UInt32Value)708U,
Gutter = (UInt32Value)0U
};
Columns columns = new Columns() { Space = "720" };
DocGrid docGrid = new DocGrid() { LinePitch = 360 };
// appen the page size and margin
properties.Append(pageSize, pageMargin, columns, docGrid);
return properties;
}
При создании элемента свойств раздела с определенной ориентацией важно соответствующим образом настроить высоту и ширину элемента PageSize. В противном случае страницы в разделе будут отображаться неправильно (если вы визуализируете альбомную часть с портретной высотой и шириной, раздел будет выглядеть как портрет).
Когда мы закончим создание свойств раздела, все, что нам нужно сделать, это добавить свойства раздела к пустым свойствам абзаца, а затем добавить свойства абзаца к абзацу.
Используя эту функцию, мы можем создать текстовый документ с различными ориентированными секциями с помощью консольной программы ниже:
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
namespace ChangeDocVariable
{
class Program
{
static void Main(string[] args)
{
using(WordprocessingDocument doc = WordprocessingDocument.Create(@"path to document", WordprocessingDocumentType.Document))
{
// Create the maindocument part
MainDocumentPart maindDocomentPart = doc.AddMainDocumentPart();
// add the document
Document document = maindDocomentPart.Document = new Document();
// add the bdoy
Body body = document.Body = new Body();
// insert a set of sections
// To insert a section we need to add a paragraph
// which contains paragaph properties
// which holds the section properties
Paragraph firstSection = new Paragraph();
ParagraphProperties firstSectionProperties = new ParagraphProperties();
firstSectionProperties.Append(CreateSectionProperties(PageOrientationValues.Portrait));
firstSection.Append(firstSectionProperties);
Paragraph secondSection = new Paragraph();
ParagraphProperties secondSectionProperties = new ParagraphProperties();
secondSectionProperties.Append(CreateSectionProperties(PageOrientationValues.Landscape));
secondSection.Append(secondSectionProperties);
Paragraph thirdSection = new Paragraph();
ParagraphProperties thirdSectionProperties = new ParagraphProperties();
thirdSectionProperties.Append(CreateSectionProperties(PageOrientationValues.Portrait));
thirdSection.Append(thirdSectionProperties);
body.Append(firstSection, secondSection, thirdSection);
// for the last section we can directly add a section properties
body.Append(CreateSectionProperties(PageOrientationValues.Landscape));
}
}
/// <summary>
/// Will create a section properties
/// </summary>
/// <param name="orientation">The wanted orientation (landscape or portrai)</param>
/// <returns>A section properties element</returns>
public static SectionProperties CreateSectionProperties(PageOrientationValues orientation)
{
// create the section properties
SectionProperties properties = new SectionProperties();
// create the height and width
UInt32Value height = orientation == (PageOrientationValues.Portrait) ? 16839U : 11907U;
UInt32Value width = orientation != (PageOrientationValues.Portrait) ? 16839U : 11907U;
// create the page size and insert the wanted orientation
PageSize pageSize = new PageSize()
{
Width = width,
Height = height,
Code = (UInt16Value)9U,
// insert the orientation
Orient = orientation };
// create the page margin
PageMargin pageMargin = new PageMargin()
{
Top = 1417,
Right = (UInt32Value)1417U,
Bottom = 1417,
Left = (UInt32Value)1417U,
Header = (UInt32Value)708U,
Footer = (UInt32Value)708U,
Gutter = (UInt32Value)0U
};
Columns columns = new Columns() { Space = "720" };
DocGrid docGrid = new DocGrid() { LinePitch = 360 };
// appen the page size and margin
properties.Append(pageSize, pageMargin, columns, docGrid);
return properties;
}
}
}
Это создаст документ с четырьмя разделами. Последние SectionProrties могут быть непосредственно добавлены в тело самого документа.