Я пытался решить эту проблему в течение нескольких дней, и у меня нет идей. Я новичок в Itextsharp и Itext7, может ли кто -нибудь помочь мне с этим? /p>
Я обнаружил, что некоторые клетки были выдвинуты в правую сторону, пока вы не увидите ее больше, но не можете полностью исправить их полностью. Некоторые ячейки исчезли, даже если зарегистрированные данные извлеченного содержания DOCX все хорошо. < /P>
Посоветуйте. В этом посте это мой первый раз задаю вопрос. Пожалуйста, укажите мои ошибки, чтобы я мог узнать больше о переполнении стека. Спасибо. Ниже приведен код с методами извлечения содержания DOCX (ProcessDocument) и CreatePDF для создания PDF и основной бизнес -логики: < /p>
private static void ProcessDocument(string filePath, string pdfPath)
{
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(filePath, false))
{
var tables = wordDoc.MainDocumentPart.Document.Body.Elements();
List rowDataList = new List();
List imageList = new List(); // To store extracted images
// Extract images from the Word document
ExtractImages(wordDoc, imageList);
// Extract and log content controls
ExtractContentControls(wordDoc);
foreach (var table in tables)
{
foreach (var row in table.Elements())
{
List cellDataList = new List();
float rowHeight = GetRowHeight(row);
foreach (var cell in row.Elements())
{
int splitCount = GetCellSplitCount(cell);
float cellWidth = GetCellWidth(cell);
bool isMerged = IsCellMerged(cell);
string cellText = GetCellText(cell);
string cellShadingColor = GetCellShadingColor(cell);
float fontSize = GetFontSize(cell);
string fontFamily = GetFontFamily(cell, out bool isBold, out bool isItalic);
Color fontColor = GetFontColor(cell.Elements
().FirstOrDefault().Elements().FirstOrDefault());
int alignment = GetCellAlignment(cell);
string fontName = fontFamily;
if (isBold) fontName += " Bold";
if (isItalic) fontName += " Italic";
cellDataList.Add(new CellData
{
SplitCount = splitCount,
Width = cellWidth,
IsMerged = isMerged,
Text = cellText,
ShadingColor = cellShadingColor,
FontSize = fontSize,
FontFamily = fontName,
FontColor = fontColor,
RowSpan = GetCellRowSpan(cell),
Alignment = alignment
});
}
rowDataList.Add(new RowData
{
Cells = cellDataList,
Height = rowHeight
});
}
}
CreatePdf(pdfPath, rowDataList, imageList); // Pass the imageList to the CreatePdf method
}
}
// Create PDF and handle merged cells with appropriate rowspan/colspan
static void CreatePdf(string pdfPath, List rowDataList, List imageList)
{
using (FileStream fs = new FileStream(pdfPath, FileMode.Create))
{
Document pdfDoc = new Document();
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, fs);
pdfDoc.Open();
// Calculate the total number of columns in the table based on the row data
int columnCount = rowDataList.Max(r => r.Cells.Sum(cell => cell.SplitCount)); // Sum of SplitCount across all rows
PdfPTable pdfTable = new PdfPTable(columnCount);
int imageIndex = 0; // Track the images added
// Log the number of columns in the table
Console.WriteLine($"Creating PDF table with {columnCount} columns.");
// Iterate through each row
foreach (var row in rowDataList)
{
Console.WriteLine($"Processing row with {row.Cells.Count} cells (height: {row.Height}).");
if (row.Cells.Count == 0)
{
Console.WriteLine("Skipping empty row data.");
continue; // Skip empty row data
}
// Create a PdfPTable with the total number of columns based on the splits
int totalColumns = row.Cells.Sum(cell => cell.SplitCount);
// Calculate column widths based on the total width of the cells
float[] columnWidths = new float[totalColumns];
int columnIndex = 0;
// Calculate total width for the row (assuming you can get the width for each cell)
float totalRowWidth = 0;
foreach (var cell in row.Cells)
{
totalRowWidth += cell.Width; // Add the width of each cell to the total row width
}
columnIndex = 0;
// Calculate proportional width for each column based on the total row width
foreach (var cellData in row.Cells)
{
// Calculate the proportional width of each column based on the total row width
columnWidths[columnIndex] = (cellData.Width / totalRowWidth) * 100f; // Percentage-based width
columnIndex += cellData.SplitCount; // Move forward by the split count
}
// Apply column widths to the table (only once per row)
pdfTable.SetWidths(columnWidths);
// Now, add each cell to the table
columnIndex = 0; // Reset column index to start at 0 for each row
foreach (var cellData in row.Cells)
{
// Log cell data
Console.WriteLine($"Processing cell at column index {columnIndex}: Text = '{cellData.Text}', RowSpan = {cellData.RowSpan}, SplitCount = {cellData.SplitCount}, Font = '{cellData.FontFamily}', FontColor = '{cellData.FontColor?.Val}', ShadingColor = '{cellData.ShadingColor}', IsMerged {cellData.IsMerged}");
// Calculate the height for empty cells
float cellHeight = row.Height;
if (string.IsNullOrEmpty(cellData.Text))
{
cellHeight = Math.Max(row.Height, 12f); // Ensure a minimum height for empty cells
}
// // List to track merged cells for RowSpan handling
List mergedColumns = new List(new bool[totalColumns]);
if (cellData.RowSpan > 1 && mergedColumns[columnIndex])
{
columnIndex += cellData.SplitCount;
}
// Load the font based on the font family
BaseFont baseFont;
if (fontDictionary.TryGetValue(cellData.FontFamily, out string fontFilePath))
{
baseFont = BaseFont.CreateFont(fontFilePath, BaseFont.CP1252, BaseFont.EMBEDDED);
}
else
{
baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED); // Fallback to Helvetica
}
// Ensure FontColor is not null, set to black if null
BaseColor fontColor = cellData.FontColor != null ? BaseColorFromHex(cellData.FontColor.Val) : BaseColor.BLACK;
Font pdfFont = new Font(baseFont, cellData.FontSize) { Color = fontColor };
// Create a Phrase with the Font
Phrase phrase = new Phrase(cellData.Text, pdfFont);
// Create a PdfPCell for this specific cell
PdfPCell pdfCell = new PdfPCell(phrase)
{
FixedHeight = cellHeight,
MinimumHeight = cellHeight,
PaddingLeft = 4,
PaddingRight = 5,
PaddingTop = 3,
PaddingBottom = 5
};
pdfCell.SetLeading(1.5f, 1.0f); // Set line spacing
// Apply the alignment from the cell's data
pdfCell.HorizontalAlignment = cellData.Alignment; // Cell alignment
// Apply vertical merge (row span)
if (cellData.RowSpan > 1)
{
pdfCell.Rowspan = cellData.RowSpan;
Console.WriteLine($"Applied RowSpan: {cellData.RowSpan} for cell text '{cellData.Text}'");
}
// Apply horizontal merge (column span)
if (cellData.SplitCount > 1)
{
pdfCell.Colspan = cellData.SplitCount;
Console.WriteLine($"Applied ColSpan: {cellData.SplitCount} for cell text '{cellData.Text}'");
}
// Set background color if present
if (!string.IsNullOrEmpty(cellData.ShadingColor))
{
pdfCell.BackgroundColor = BaseColorFromHex(cellData.ShadingColor);
Console.WriteLine($"Applied Shading Color: {cellData.ShadingColor} for cell text '{cellData.Text}'");
}
// Add the cell to the table
pdfTable.AddCell(pdfCell);
Console.WriteLine($"Added cell to table at column index {columnIndex}");
// Update column index to account for merged cells (if any)
columnIndex += cellData.SplitCount;
}
// Add an image to the PDF if available
if (imageIndex < imageList.Count)
{
var image = Image.GetInstance(imageList[imageIndex].ImagePath);
image.ScaleToFit(100, 100); // Scale image if needed
pdfDoc.Add(image);
imageIndex++;
}
}
// Add the constructed table to the PDF document
pdfDoc.Add(pdfTable);
pdfDoc.Close();
writer.Close();
}
}
< /code>
Я попытался удалить коды один за другим, пока не нашел проблему, и она всегда заканчивается одинаковой. Без кода слияния ячейки дизайн хорош. И если я добавлю кое -что или несколько алгоритмов расчета ширины ячейки, вертикальное слияние ячейки больше не будет работать. Если не все, большинство, кто выходит на поиск Google и переполнение стека, я прочитал, но никто не говорит об этом.
Подробнее здесь: https://stackoverflow.com/questions/794 ... itextsharp
Почему применение Rowspan разрушает дизайн в Itextsharp? ⇐ C#
Место общения программистов C#
-
Anonymous
1739450568
Anonymous
Я пытался решить эту проблему в течение нескольких дней, и у меня нет идей. Я новичок в Itextsharp и Itext7, может ли кто -нибудь помочь мне с этим? /p>
Я обнаружил, что некоторые клетки были выдвинуты в правую сторону, пока вы не увидите ее больше, но не можете полностью исправить их полностью. Некоторые ячейки исчезли, даже если зарегистрированные данные извлеченного содержания DOCX все хорошо. < /P>
Посоветуйте. В этом посте это мой первый раз задаю вопрос. Пожалуйста, укажите мои ошибки, чтобы я мог узнать больше о переполнении стека. Спасибо. Ниже приведен код с методами извлечения содержания DOCX (ProcessDocument) и CreatePDF для создания PDF и основной бизнес -логики: < /p>
private static void ProcessDocument(string filePath, string pdfPath)
{
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(filePath, false))
{
var tables = wordDoc.MainDocumentPart.Document.Body.Elements();
List rowDataList = new List();
List imageList = new List(); // To store extracted images
// Extract images from the Word document
ExtractImages(wordDoc, imageList);
// Extract and log content controls
ExtractContentControls(wordDoc);
foreach (var table in tables)
{
foreach (var row in table.Elements())
{
List cellDataList = new List();
float rowHeight = GetRowHeight(row);
foreach (var cell in row.Elements())
{
int splitCount = GetCellSplitCount(cell);
float cellWidth = GetCellWidth(cell);
bool isMerged = IsCellMerged(cell);
string cellText = GetCellText(cell);
string cellShadingColor = GetCellShadingColor(cell);
float fontSize = GetFontSize(cell);
string fontFamily = GetFontFamily(cell, out bool isBold, out bool isItalic);
Color fontColor = GetFontColor(cell.Elements
().FirstOrDefault().Elements().FirstOrDefault());
int alignment = GetCellAlignment(cell);
string fontName = fontFamily;
if (isBold) fontName += " Bold";
if (isItalic) fontName += " Italic";
cellDataList.Add(new CellData
{
SplitCount = splitCount,
Width = cellWidth,
IsMerged = isMerged,
Text = cellText,
ShadingColor = cellShadingColor,
FontSize = fontSize,
FontFamily = fontName,
FontColor = fontColor,
RowSpan = GetCellRowSpan(cell),
Alignment = alignment
});
}
rowDataList.Add(new RowData
{
Cells = cellDataList,
Height = rowHeight
});
}
}
CreatePdf(pdfPath, rowDataList, imageList); // Pass the imageList to the CreatePdf method
}
}
// Create PDF and handle merged cells with appropriate rowspan/colspan
static void CreatePdf(string pdfPath, List rowDataList, List imageList)
{
using (FileStream fs = new FileStream(pdfPath, FileMode.Create))
{
Document pdfDoc = new Document();
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, fs);
pdfDoc.Open();
// Calculate the total number of columns in the table based on the row data
int columnCount = rowDataList.Max(r => r.Cells.Sum(cell => cell.SplitCount)); // Sum of SplitCount across all rows
PdfPTable pdfTable = new PdfPTable(columnCount);
int imageIndex = 0; // Track the images added
// Log the number of columns in the table
Console.WriteLine($"Creating PDF table with {columnCount} columns.");
// Iterate through each row
foreach (var row in rowDataList)
{
Console.WriteLine($"Processing row with {row.Cells.Count} cells (height: {row.Height}).");
if (row.Cells.Count == 0)
{
Console.WriteLine("Skipping empty row data.");
continue; // Skip empty row data
}
// Create a PdfPTable with the total number of columns based on the splits
int totalColumns = row.Cells.Sum(cell => cell.SplitCount);
// Calculate column widths based on the total width of the cells
float[] columnWidths = new float[totalColumns];
int columnIndex = 0;
// Calculate total width for the row (assuming you can get the width for each cell)
float totalRowWidth = 0;
foreach (var cell in row.Cells)
{
totalRowWidth += cell.Width; // Add the width of each cell to the total row width
}
columnIndex = 0;
// Calculate proportional width for each column based on the total row width
foreach (var cellData in row.Cells)
{
// Calculate the proportional width of each column based on the total row width
columnWidths[columnIndex] = (cellData.Width / totalRowWidth) * 100f; // Percentage-based width
columnIndex += cellData.SplitCount; // Move forward by the split count
}
// Apply column widths to the table (only once per row)
pdfTable.SetWidths(columnWidths);
// Now, add each cell to the table
columnIndex = 0; // Reset column index to start at 0 for each row
foreach (var cellData in row.Cells)
{
// Log cell data
Console.WriteLine($"Processing cell at column index {columnIndex}: Text = '{cellData.Text}', RowSpan = {cellData.RowSpan}, SplitCount = {cellData.SplitCount}, Font = '{cellData.FontFamily}', FontColor = '{cellData.FontColor?.Val}', ShadingColor = '{cellData.ShadingColor}', IsMerged {cellData.IsMerged}");
// Calculate the height for empty cells
float cellHeight = row.Height;
if (string.IsNullOrEmpty(cellData.Text))
{
cellHeight = Math.Max(row.Height, 12f); // Ensure a minimum height for empty cells
}
// // List to track merged cells for RowSpan handling
List mergedColumns = new List(new bool[totalColumns]);
if (cellData.RowSpan > 1 && mergedColumns[columnIndex])
{
columnIndex += cellData.SplitCount;
}
// Load the font based on the font family
BaseFont baseFont;
if (fontDictionary.TryGetValue(cellData.FontFamily, out string fontFilePath))
{
baseFont = BaseFont.CreateFont(fontFilePath, BaseFont.CP1252, BaseFont.EMBEDDED);
}
else
{
baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED); // Fallback to Helvetica
}
// Ensure FontColor is not null, set to black if null
BaseColor fontColor = cellData.FontColor != null ? BaseColorFromHex(cellData.FontColor.Val) : BaseColor.BLACK;
Font pdfFont = new Font(baseFont, cellData.FontSize) { Color = fontColor };
// Create a Phrase with the Font
Phrase phrase = new Phrase(cellData.Text, pdfFont);
// Create a PdfPCell for this specific cell
PdfPCell pdfCell = new PdfPCell(phrase)
{
FixedHeight = cellHeight,
MinimumHeight = cellHeight,
PaddingLeft = 4,
PaddingRight = 5,
PaddingTop = 3,
PaddingBottom = 5
};
pdfCell.SetLeading(1.5f, 1.0f); // Set line spacing
// Apply the alignment from the cell's data
pdfCell.HorizontalAlignment = cellData.Alignment; // Cell alignment
// Apply vertical merge (row span)
if (cellData.RowSpan > 1)
{
pdfCell.Rowspan = cellData.RowSpan;
Console.WriteLine($"Applied RowSpan: {cellData.RowSpan} for cell text '{cellData.Text}'");
}
// Apply horizontal merge (column span)
if (cellData.SplitCount > 1)
{
pdfCell.Colspan = cellData.SplitCount;
Console.WriteLine($"Applied ColSpan: {cellData.SplitCount} for cell text '{cellData.Text}'");
}
// Set background color if present
if (!string.IsNullOrEmpty(cellData.ShadingColor))
{
pdfCell.BackgroundColor = BaseColorFromHex(cellData.ShadingColor);
Console.WriteLine($"Applied Shading Color: {cellData.ShadingColor} for cell text '{cellData.Text}'");
}
// Add the cell to the table
pdfTable.AddCell(pdfCell);
Console.WriteLine($"Added cell to table at column index {columnIndex}");
// Update column index to account for merged cells (if any)
columnIndex += cellData.SplitCount;
}
// Add an image to the PDF if available
if (imageIndex < imageList.Count)
{
var image = Image.GetInstance(imageList[imageIndex].ImagePath);
image.ScaleToFit(100, 100); // Scale image if needed
pdfDoc.Add(image);
imageIndex++;
}
}
// Add the constructed table to the PDF document
pdfDoc.Add(pdfTable);
pdfDoc.Close();
writer.Close();
}
}
< /code>
Я попытался удалить коды один за другим, пока не нашел проблему, и она всегда заканчивается одинаковой. Без кода слияния ячейки дизайн хорош. И если я добавлю кое -что или несколько алгоритмов расчета ширины ячейки, вертикальное слияние ячейки больше не будет работать. Если не все, большинство, кто выходит на поиск Google и переполнение стека, я прочитал, но никто не говорит об этом.
Подробнее здесь: [url]https://stackoverflow.com/questions/79436208/why-does-applying-rowspan-ruins-the-design-in-itextsharp[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия