Создаётся битый файл iTextSharp - C#
Формулировка задачи:
Доброго дня. Создаю PDF файл с помощью библиотеки iTextSharp, но он создаётся битым, то есть содержимое не открывается. До этого всё работало. За комментировал весь код который передаёт в файл данные и оставил тольк следующее:
То есть на данный момент должен создаваться пустой файл, но вместо этого получается битый файл. Пишет следующее при открытие через Adobe Reader: "формат файла не поддерживается или файл был поврежден"
В чём может быть проблема?
За ранее спасибо.
iTextSharp.text.Rectangle rec = new iTextSharp.text.Rectangle(PageSize.A4);
Document doc = new Document(rec, 36, 36, 50, 50);
////добавление шрифта поддерживающего русский язык
BaseFont baseFont = BaseFont.CreateFont(@"..\..\arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.NORMAL);
try
{
using (FileStream fs = new FileStream(@"..\..\test.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
iTextSharp.text.Image img;
doc.Open();
doc.Close();
MessageBox.Show("Файл полностью готов.");Решение задачи: «Создаётся битый файл iTextSharp»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Security;
using iTextSharp.text.html.simpleparser;
namespace FilePDF
{
public partial class Form1 : Form
{
private List<string> pathImages = new List<string>();
public Form1()
{
InitializeComponent();
}
private void buttonCratePDF_Click(object sender, EventArgs e)
{
//поля титульного листа
string filePath;
string fileName;
string authorName;
string theme;
string plase;
string year;
fileName = textBoxNamePDF_tp.Text;
authorName = textBoxAuthor_tp.Text;
theme = textBoxTheme_tp.Text;
plase = textBoxPlace_tp.Text;
year = textBoxYear_tp.Text;
filePath = @"..\.." + fileName + ".pdf";
//размер страницы
iTextSharp.text.Rectangle rec = new iTextSharp.text.Rectangle(PageSize.A4);
Document doc = new Document(rec, 36, 72, 108, 180);
////добавление шрифта поддерживающего русский язык
BaseFont baseFont = BaseFont.CreateFont(@"..\..\arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.NORMAL);
try
{
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
// Read in the contents of the Receipt.htm file...
string contents = File.ReadAllText(@"../../Titlepage.html");
// Replace the placeholders with the user-specified text
contents = contents.Replace("[THEME]", theme);
contents = contents.Replace("[AUTHOR]", authorName);
contents = contents.Replace("[CITY]", plase);
contents = contents.Replace("[YEAR]", year);
//Parse the HTML string into a collection of elements...
var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), null);
iTextSharp.text.Image img;
doc.Open();
// Enumerate the elements, adding each one to the Document...
foreach (var htmlElement in parsedHtmlElements)
doc.Add(htmlElement as IElement);
var t = new PdfPTable(1);
t.WidthPercentage = 100;
var c = new PdfPCell();
c.VerticalAlignment = Element.ALIGN_MIDDLE;
c.MinimumHeight = doc.PageSize.Height - (doc.BottomMargin + doc.TopMargin);
Paragraph authorNameParagraph = new Paragraph(authorName, font);
authorNameParagraph.Alignment = Element.ALIGN_CENTER;
Paragraph themeParagraph = new Paragraph("Тема: " + theme, font);
authorNameParagraph.Alignment = Element.ALIGN_CENTER;
Paragraph plaseAndYearParagraph = new Paragraph(plase + " " + year, font);
authorNameParagraph.Alignment = Element.ALIGN_CENTER;
c.AddElement(authorNameParagraph);
c.AddElement(themeParagraph);
c.AddElement(plaseAndYearParagraph);
//Add the cell to the paragraph
t.AddCell(c);
//Add the table to the document
doc.Add(t);
foreach (string element in pathImages)
{
img = iTextSharp.text.Image.GetInstance(element);
img.ScaleToFit(300f, 300f);
doc.Add(img);
}
doc.Close();
MessageBox.Show("Файл создан, добавляются страницы.");
AddPageNumber(filePath);
MessageBox.Show("Файл полностью готов.");
}
}
catch (DocumentException ex)
{
Console.WriteLine(ex.Message);
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
}
}
protected void AddPageNumber(string filePath)//возможна проблема, когда файл получается слишком большой.(кажется)
{
byte[] bytes = File.ReadAllBytes(filePath);
iTextSharp.text.Font blackFont = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
using (MemoryStream stream = new MemoryStream())
{
PdfReader reader = new PdfReader(bytes);
using (PdfStamper stamper = new PdfStamper(reader, stream))
{
int pages = reader.NumberOfPages;
for (int i = 2; i <= pages; i++)
{
ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_RIGHT, new Phrase(i.ToString(), blackFont), 568f, 15f, 0);
}
}
bytes = stream.ToArray();
}
File.WriteAllBytes(filePath, bytes);
}
private void textBoxNamePDF_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void InitializeOpenFileDialog()
{
// Set the file dialog to filter for graphics files.
this.openFileDialog1.Filter =
"Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" +
"All files (*.*)|*.*";
// Allow the user to select multiple images.
this.openFileDialog1.Multiselect = true;
this.openFileDialog1.Title = "My Image Browser";
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Multiselect = true;
openFile.Filter = "Image Files(*.BMP;*.JPG;*.GIF;*.TIF;*.WMF)|*.BMP;*.JPG;*.GIF;*.TIF;*.WMF|All files (*.*)|*.*";
//openFile.FilterIndex = 2;//для выбора начального расширения
if (openFile.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(openFile.FileName);
//textBox1.Text += openFile.FileNames;
pathImages.Clear();
foreach (string element in openFile.FileNames)
{
pathImages.Add(element);
}
textBox1.Text = String.Join(Environment.NewLine, pathImages);
}
}
}
}