I want to read a PDF file using itextsharp 5, and create a new PDF file with the left half of each page of the original PDF, discarding the right half. I wrote the following code, but the result is corrupt and cannot be opened with Acrobat Reader (opening it with Chrome works though). How can I make a PDF that works with Acrobat Reader?
private byte[] ObtenerMitadPdf(byte[] Contenido)
{
using (var pdfReader = new PdfReader(Contenido))
{
using (var memoryStream = new MemoryStream())
{
using (var documento = new Document())
using (var pdfWriter = PdfWriter.GetInstance(documento, memoryStream))
{
pdfWriter.CloseStream = false;
documento.Open();
for (int i = 1; i <= pdfReader.NumberOfPages; i++)
{
var pagina = pdfWriter.GetImportedPage(pdfReader, i);
var tamañoPagina = pdfReader.GetPageSizeWithRotation(i);
var nuevoTamaño = new Rectangle(tamañoPagina.Left, tamañoPagina.Bottom,
tamañoPagina.Left + (tamañoPagina.Width / 2), tamañoPagina.Top, tamañoPagina.Rotation);
if (tamañoPagina.Rotation == 90)
{
pdfWriter.DirectContent.AddTemplate(pagina, 0, -1, 1, 0, 0, tamañoPagina.Height);
}
else
{
pdfWriter.DirectContent.AddTemplate(pagina, 0, 0);
}
documento.SetPageSize(nuevoTamaño);
documento.NewPage();
}
}
return memoryStream.ToArray();
}
}
}
var pdfWriter = PdfWriter.GetInstance(documento, memoryStream)into ausingblock. Closing theDocumentwill implicitly close thePdfWriter. Other than that your approach is unnecessarily complicated, you can simply change the crop boxes of thePdfReaderand write that version using a ` PdfStamper`. - mkl