Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 20 additions & 11 deletions src/EPPlus.Export.Pdf/DocumentObjects/PdfBorderRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -282,13 +282,24 @@ private void DrawDoubleBorder(PdfContentStream contentStream, PdfCellBorderData
contentStream.AddCommand($"{PdfCellBorderData.DoubleWidth.ToPdfString()} w");
contentStream.AddCommand(border.BorderStyle != ExcelBorderStyle.Dotted ? (border.LineType == LineType.DiagonalUp || border.LineType == LineType.DiagonalDown ? "0 J" : "2 J") : "1 J");
contentStream.AddCommand(PdfCellBorderData.NoDash);
if ((border.LineType == LineType.DiagonalUp || border.LineType == LineType.DiagonalDown) && DiagonalUp.BorderStyle != ExcelBorderStyle.None && DiagonalDown.BorderStyle != ExcelBorderStyle.None)

double idx = ix2 - ix1, idy = iy2 - iy1;
double odx = ox2 - ox1, ody = oy2 - oy1;
double iLen = System.Math.Sqrt(idx * idx + idy * idy);
double oLen = System.Math.Sqrt(odx * odx + ody * ody);

// Only split the line to leave the mid-gap when both segments have real length;
// a zero-length (degenerate / zero-size cell) segment would divide by zero -> NaN operands.
bool diagDoubleGap =
(border.LineType == LineType.DiagonalUp || border.LineType == LineType.DiagonalDown)
&& DiagonalUp.BorderStyle != ExcelBorderStyle.None
&& DiagonalDown.BorderStyle != ExcelBorderStyle.None
&& iLen > 1e-6 && oLen > 1e-6;

if (diagDoubleGap)
{
double dx = ix2 - ix1;
double dy = iy2 - iy1;
double length = System.Math.Sqrt(dx * dx + dy * dy);
double ux = dx / length;
double uy = dy / length;
double ux = idx / iLen;
double uy = idy / iLen;
double midX = (ix1 + ix2) / 2.0;
double midY = (iy1 + iy2) / 2.0;
double leftDist = 0.25;
Expand All @@ -301,11 +312,9 @@ private void DrawDoubleBorder(PdfContentStream contentStream, PdfCellBorderData
contentStream.AddCommand($"{xA.ToPdfStringF4()} {yA.ToPdfStringF4()} l");
contentStream.AddCommand($"{xB.ToPdfStringF4()} {yB.ToPdfStringF4()} m");
contentStream.AddCommand($"{ix2.ToPdfStringF4()} {iy2.ToPdfStringF4()} l");
dx = ox2 - ox1;
dy = oy2 - oy1;
length = System.Math.Sqrt(dx * dx + dy * dy);
ux = dx / length;
uy = dy / length;

ux = odx / oLen;
uy = ody / oLen;
midX = (ox1 + ox2) / 2.0;
midY = (oy1 + oy2) / 2.0;
leftDist = 2.15;
Expand Down
8 changes: 8 additions & 0 deletions src/EPPlus.Export.Pdf/Helpers/ImageLimits.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,14 @@ internal static class ImageLimits
/// <summary>Upper bound on bytes produced by a single inflate (anti decompression-bomb).</summary>
internal const long MaxDecodedBytes = 512L * 1024 * 1024;

internal const long MaxDecodeWorkingBytes = 256L * 1024 * 1024;

internal static bool IsDecodeAllowed(int width, int height, int bytesPerPixel)
{
if (!IsAllowed(width, height, 1)) return false; // dimension + 100 MP guard
return (long)width * height * bytesPerPixel <= MaxDecodeWorkingBytes;
}

/// <summary>
/// True only when width/height are positive, within range, and width*height*bytesPerPixel
/// stays within the pixel and byte ceilings. All arithmetic is done in long, so this never
Expand Down
2 changes: 1 addition & 1 deletion src/EPPlus.Export.Pdf/Helpers/JpegCmykHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ private static bool Decode(byte[] d, out int width, out int height, out byte[] g
i = segEnd;
}

if (!ImageLimits.IsAllowed(W, H, 4)) return false;
if (!ImageLimits.IsDecodeAllowed(W, H, 32)) return false;
if (adobeTransform == 2) return false; // YCCK -> handled by the transcoder

int Hmax = 1, Vmax = 1;
Expand Down
2 changes: 1 addition & 1 deletion src/EPPlus.Export.Pdf/Helpers/JpegProgressiveHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ private static byte[] Transform(byte[] d)
W = ((d[p + 3] & 0xFF) << 8) | (d[p + 4] & 0xFF);
int nc = d[p + 5] & 0xFF;
if (nc != 3) return null;
if (!ImageLimits.IsAllowed(W, H, 4)) return null;
if (!ImageLimits.IsDecodeAllowed(W, H, 12)) return null;
for (int c = 0; c < nc; c++)
{
int q = p + 6 + c * 3;
Expand Down
20 changes: 19 additions & 1 deletion src/EPPlus.Export.Pdf/Helpers/PdfString.cs
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,20 @@ internal static bool IsDangerousUriScheme(string uri)
{
if (string.IsNullOrEmpty(uri)) return false;

// Normalize: percent-decode one level, then drop spaces + control chars, so
// "java\tscript:", " javascript:", "java%73cript:" and "javascript%3A..."
// all resolve to their real scheme before the blocklist check below.
var sb = new System.Text.StringBuilder(uri.Length);
foreach (char c in uri) if (c > ' ') sb.Append(c); // drop spaces + control chars
for (int i = 0; i < uri.Length; i++)
{
char c = uri[i];
if (c == '%' && i + 2 < uri.Length && IsHex(uri[i + 1]) && IsHex(uri[i + 2]))
{
c = (char)((HexVal(uri[i + 1]) << 4) | HexVal(uri[i + 2]));
i += 2;
}
if (c > ' ') sb.Append(c); // drop spaces + control chars
}
string norm = sb.ToString();

int colon = norm.IndexOf(':');
Expand All @@ -168,5 +180,11 @@ internal static bool IsDangerousUriScheme(string uri)
return false;
}
}

private static bool IsHex(char c) =>
(c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');

private static int HexVal(char c) =>
c <= '9' ? c - '0' : (char.ToLowerInvariant(c) - 'a' + 10);
}
}
20 changes: 12 additions & 8 deletions src/EPPlus.Export.Pdf/Helpers/PngDecoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ internal static byte[] ReadPngIdat(byte[] d, out byte[] palette)
int len = ReadBE32(d, p);
string type = Ascii(d, p + 4, 4);
int dataStart = p + 8;
if (len < 0 || dataStart + len + 4 > d.Length) break;
long end = (long)dataStart + len + 4;
if (len < 0 || end > d.Length) break;
if (type == "PLTE")
{
palette = new byte[len];
Expand All @@ -80,8 +81,9 @@ internal static void DecodePngTruecolor(byte[] pngBytes, int width, int height,
const int channels = 3;
if (!ImageLimits.IsAllowed(width, height, channels))
throw new InvalidDataException("PNG dimensions exceed the allowed limit.");
byte[] filtered = PdfFlate.Decompress(ReadPngIdat(pngBytes, out byte[] _));
int stride = width * channels;
long maxFiltered = (long)height * (stride + 1);
byte[] filtered = PdfFlate.Decompress(ReadPngIdat(pngBytes, out byte[] _), maxFiltered);
var rgb = new byte[width * height * channels];
var prev = new byte[stride];
var cur = new byte[stride];
Expand Down Expand Up @@ -121,9 +123,9 @@ internal static void DecodePngWithAlpha(byte[] pngBytes, int width, int height,
int colorChannels = colorType == 6 ? 3 : 1;
if (!ImageLimits.IsAllowed(width, height, channels))
throw new InvalidDataException("PNG dimensions exceed the allowed limit.");
byte[] filtered = PdfFlate.Decompress(ReadPngIdat(pngBytes, out byte[] _));

int stride = width * channels;
int stride = width * channels; // channels = 4 or 2
long maxFiltered = (long)height * (stride + 1);
byte[] filtered = PdfFlate.Decompress(ReadPngIdat(pngBytes, out byte[] _), maxFiltered);
var color = new byte[width * height * colorChannels];
var alpha = new byte[width * height];
var prev = new byte[stride];
Expand Down Expand Up @@ -193,7 +195,8 @@ internal static bool TryReadChunk(byte[] d, string chunkType, out byte[] data)
int len = ReadBE32(d, p);
string type = Ascii(d, p + 4, 4);
int dataStart = p + 8;
if (len < 0 || dataStart + len + 4 > d.Length) break;
long end = (long)dataStart + len + 4;
if (len < 0 || end > d.Length) break;
if (type == chunkType)
{
data = new byte[len];
Expand All @@ -212,9 +215,10 @@ internal static bool DecodeIndexedAlpha(byte[] pngBytes, int width, int height,
if (!TryReadChunk(pngBytes, "tRNS", out byte[] trns) || trns == null || trns.Length == 0)
return false;
if (!ImageLimits.IsAllowed(width, height, 1)) return false;
byte[] filtered = PdfFlate.Decompress(ReadPngIdat(pngBytes, out byte[] _));
const int bpp = 1;
int stride = (width * bitDepth + 7) / 8;
long maxFiltered = (long)height * (stride + 1);
byte[] filtered = PdfFlate.Decompress(ReadPngIdat(pngBytes, out byte[] _), maxFiltered);
const int bpp = 1;
var prev = new byte[stride];
var cur = new byte[stride];
var alpha = new byte[width * height];
Expand Down
5 changes: 4 additions & 1 deletion src/EPPlus/Export/PdfExport/Data/PdfCellCollection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ internal class PdfCellCollection

private PdfCell[,] Cells;

internal const long MaxCells = 64L * 1024 * 1024;

public PdfCellCollection(int fromRow, int toRow, int fromColumn, int toColumn)
{
if(fromRow > toRow) throw new ArgumentOutOfRangeException("Invalid row range. toRow must be equal or greater than fromRow");
Expand All @@ -33,7 +35,8 @@ public PdfCellCollection(int fromRow, int toRow, int fromColumn, int toColumn)
ToColumn = toColumn;
int x = toRow - fromRow + 1;
int y = toColumn - fromColumn + 1;

if ((long)x * y > MaxCells)
throw new System.InvalidOperationException($"PDF export range is too large ({x} rows × {y} columns). " + "Reduce the print area or the worksheet's used range.");
Cells = new PdfCell[x, y];
}

Expand Down
20 changes: 14 additions & 6 deletions src/EPPlus/Export/PdfExport/EPPlusToPdfWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -537,15 +537,23 @@ private void GetPrintTitles(PdfRenderSettings pageSettings, PdfWorksheet pdfShee
//Check PdfPageSettings overrides
if (pageSettings.RowsToRepeatAtTop != null)
{
ExcelAddressBase repeatRows = new ExcelAddressBase(pageSettings.RowsToRepeatAtTop);
pdfSheet.PrintTitleRowFrom = repeatRows._fromRow;
pdfSheet.PrintTitleRowTo = repeatRows._toRow;
try
{
var repeatRows = new ExcelAddressBase(pageSettings.RowsToRepeatAtTop);
pdfSheet.PrintTitleRowFrom = repeatRows._fromRow;
pdfSheet.PrintTitleRowTo = repeatRows._toRow;
}
catch {}
}
if (pageSettings.ColumnsToRepeatAtLeft != null)
{
ExcelAddressBase repeatCols = new ExcelAddressBase(pageSettings.ColumnsToRepeatAtLeft);
pdfSheet.PrintTitleColFrom = repeatCols._fromCol;
pdfSheet.PrintTitleColTo = repeatCols._toCol;
try
{
var repeatCols = new ExcelAddressBase(pageSettings.ColumnsToRepeatAtLeft);
pdfSheet.PrintTitleColFrom = repeatCols._fromCol;
pdfSheet.PrintTitleColTo = repeatCols._toCol;
}
catch {}
}
foreach (var range in pdfSheet.Ranges)
MarkPrintTitleCells(pdfSheet, range);
Expand Down
3 changes: 1 addition & 2 deletions src/EPPlus/Export/PdfExport/Settings/GetPdfSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -227,8 +227,7 @@ private static PdfPageSize GetPageSize(ePaperSize PaperSize)
case ePaperSize.A3ExtraTransverse:
return PdfPageSize.A3ExtraTransverse;
default:
//should return custom paper size instead.
throw new ArgumentOutOfRangeException(nameof(PaperSize), PaperSize, "Unsupported paper size.");
return PdfPageSize.A4;
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ internal static PdfHeaderFooter GetTextFormats(PdfRenderSettings pageSettings, P
text += DateTime.Now.ToString($"yyyy-MM-dd");
break;
case ExcelHeaderFooterFormattingCodes.FileName:
text += ws._package.File.Name;
text += ws._package.File?.Name ?? "";
break;
case ExcelHeaderFooterFormattingCodes.NumberOfPages:
text += "000";
Expand All @@ -93,7 +93,7 @@ internal static PdfHeaderFooter GetTextFormats(PdfRenderSettings pageSettings, P
text += DateTime.Now.ToString("HH:mm");
break;
case ExcelHeaderFooterFormattingCodes.FilePath:
text += ws._package.File.Directory.FullName + "\\";
text += ws._package.File?.Directory != null ? ws._package.File.Directory.FullName + "\\" : "";
break;
default:
text += hf.Text;
Expand Down
24 changes: 22 additions & 2 deletions src/EPPlus/Export/PdfExport/TextMapping/PdfHyperlinkResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,19 @@ internal static string NormalizeExternalTarget(string target)
if (string.IsNullOrEmpty(target)) return null;
if (IsWebUri(target)) return target;
if (Uri.TryCreate(target, UriKind.Absolute, out var u))
return u.IsFile ? u.AbsoluteUri : target;
{
switch (u.Scheme.ToLowerInvariant())
{
case "http":
case "https":
case "ftp":
case "ftps":
case "mailto":
return target;
default:
return null;
}
}
return null;
}

Expand All @@ -85,7 +97,15 @@ internal static bool TryResolveInternalLink(ExcelWorksheet linkSheet, string tar
return row > 0 && col > 0;
}
}
var addr = new ExcelAddress(target);
ExcelAddress addr;
try
{
addr = new ExcelAddress(target);
}
catch
{
return false;
}
var sheet = string.IsNullOrEmpty(addr.WorkSheetName) ? linkSheet : wb.Worksheets[addr.WorkSheetName];
if (sheet == null) return false;
targetSheet = sheet.Name; row = addr.Start.Row; col = addr.Start.Column;
Expand Down
Loading