- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我对 PDF 有一个棘手的要求
我需要在我的 pdf 中搜索特定字符串 - 属性编号:
每次找到这个,我都需要在上面添加一个分页符
我可以访问 IText 和 Spire.PDF,我先看 IText
我从这里的其他帖子确定我需要使用 PDF Stamper
下面的逻辑添加了一个有效的新页面
但是,在我的例子中,我只需要一个分页符而不是一个空白页
var newFile = @"c:\temp\full.pdf";
var dest = @"c:\temp\dest.pdf";
var reader = new PdfReader(newFile);
if (File.Exists(dest))
{
File.Delete(dest);
}
var stamper = new PdfStamper(reader, new FileStream(dest, FileMode.CreateNew));
var total = reader.NumberOfPages + 1;
for (var pageNumber = total; pageNumber > 0; pageNumber--)
{
var pageContent = reader.GetPageContent(pageNumber);
stamper.InsertPage(pageNumber, PageSize.A4);
}
stamper.Close();
reader.Close();
下图显示了一个示例,所以这实际上是 3 页,现有页面,在第一次出现的属性编号上方插入一个新的分页符:
在第二次出现之前需要另一个分页符
最佳答案
此答案分享了使用 iText 和 Java 查找 PDF 中所有出现的特定文本并在上方插入分页符的概念验证。将它移植到 iTextSharp 和 C# 应该不会太难。
此外,对于生产使用,必须添加一些额外的代码,因为目前代码做出了一些假设,例如假定非旋转页面。此外,它根本不处理注释。
这个任务实际上是两个任务的组合,查找和插入分页符,因此我们需要
为了提取自定义文本的位置,我们扩展了 iText LocationTextExtractionStrategy
以允许提取自定义文本字符串的位置,实际上是正则表达式的匹配项:
public class SearchTextLocationExtractionStrategy extends LocationTextExtractionStrategy {
public SearchTextLocationExtractionStrategy(Pattern pattern) {
super(new TextChunkLocationStrategy() {
public TextChunkLocation createLocation(TextRenderInfo renderInfo, LineSegment baseline) {
// while baseLine has been changed to not neutralize
// effects of rise, ascentLine and descentLine explicitly
// have not: We want the actual positions.
return new AscentDescentTextChunkLocation(baseline, renderInfo.getAscentLine(),
renderInfo.getDescentLine(), renderInfo.getSingleSpaceWidth());
}
});
this.pattern = pattern;
}
static Field locationalResultField = null;
static Method filterTextChunksMethod = null;
static Method startsWithSpaceMethod = null;
static Method endsWithSpaceMethod = null;
static Field textChunkTextField = null;
static Method textChunkSameLineMethod = null;
static {
try {
locationalResultField = LocationTextExtractionStrategy.class.getDeclaredField("locationalResult");
locationalResultField.setAccessible(true);
filterTextChunksMethod = LocationTextExtractionStrategy.class.getDeclaredMethod("filterTextChunks",
List.class, TextChunkFilter.class);
filterTextChunksMethod.setAccessible(true);
startsWithSpaceMethod = LocationTextExtractionStrategy.class.getDeclaredMethod("startsWithSpace",
String.class);
startsWithSpaceMethod.setAccessible(true);
endsWithSpaceMethod = LocationTextExtractionStrategy.class.getDeclaredMethod("endsWithSpace", String.class);
endsWithSpaceMethod.setAccessible(true);
textChunkTextField = TextChunk.class.getDeclaredField("text");
textChunkTextField.setAccessible(true);
textChunkSameLineMethod = TextChunk.class.getDeclaredMethod("sameLine", TextChunk.class);
textChunkSameLineMethod.setAccessible(true);
} catch (NoSuchFieldException | SecurityException | NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Collection<TextRectangle> getLocations(TextChunkFilter chunkFilter) {
Collection<TextRectangle> result = new ArrayList<>();
try {
List<TextChunk> filteredTextChunks = (List<TextChunk>) filterTextChunksMethod.invoke(this,
locationalResultField.get(this), chunkFilter);
Collections.sort(filteredTextChunks);
StringBuilder sb = new StringBuilder();
List<AscentDescentTextChunkLocation> locations = new ArrayList<>();
TextChunk lastChunk = null;
for (TextChunk chunk : filteredTextChunks) {
String chunkText = (String) textChunkTextField.get(chunk);
if (lastChunk == null) {
// Nothing to compare with at the end
} else if ((boolean) textChunkSameLineMethod.invoke(chunk, lastChunk)) {
// we only insert a blank space if the trailing character of the previous string
// wasn't a space,
// and the leading character of the current string isn't a space
if (isChunkAtWordBoundary(chunk, lastChunk)
&& !((boolean) startsWithSpaceMethod.invoke(this, chunkText))
&& !((boolean) endsWithSpaceMethod.invoke(this, chunkText))) {
sb.append(' ');
LineSegment spaceBaseLine = new LineSegment(lastChunk.getEndLocation(),
chunk.getStartLocation());
locations.add(new AscentDescentTextChunkLocation(spaceBaseLine, spaceBaseLine, spaceBaseLine,
chunk.getCharSpaceWidth()));
}
} else {
assert sb.length() == locations.size();
Matcher matcher = pattern.matcher(sb);
while (matcher.find()) {
int i = matcher.start();
Vector baseStart = locations.get(i).getStartLocation();
TextRectangle textRectangle = new TextRectangle(matcher.group(), baseStart.get(Vector.I1),
baseStart.get(Vector.I2));
for (; i < matcher.end(); i++) {
AscentDescentTextChunkLocation location = locations.get(i);
textRectangle.add(location.getAscentLine().getBoundingRectange());
textRectangle.add(location.getDescentLine().getBoundingRectange());
}
result.add(textRectangle);
}
sb.setLength(0);
locations.clear();
}
sb.append(chunkText);
locations.add((AscentDescentTextChunkLocation) chunk.getLocation());
lastChunk = chunk;
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
@Override
public void renderText(TextRenderInfo renderInfo) {
for (TextRenderInfo info : renderInfo.getCharacterRenderInfos())
super.renderText(info);
}
public static class AscentDescentTextChunkLocation extends TextChunkLocationDefaultImp {
public AscentDescentTextChunkLocation(LineSegment baseLine, LineSegment ascentLine, LineSegment descentLine,
float charSpaceWidth) {
super(baseLine.getStartPoint(), baseLine.getEndPoint(), charSpaceWidth);
this.ascentLine = ascentLine;
this.descentLine = descentLine;
}
public LineSegment getAscentLine() {
return ascentLine;
}
public LineSegment getDescentLine() {
return descentLine;
}
final LineSegment ascentLine;
final LineSegment descentLine;
}
public class TextRectangle extends Rectangle2D.Float {
public TextRectangle(final String text, final float xStart, final float yStart) {
super(xStart, yStart, 0, 0);
this.text = text;
}
public String getText() {
return text;
}
final String text;
}
final Pattern pattern;
}
( SearchTextLocationExtractionStrategy.java )
由于基类的一些必要成员是private或package private的,我们不得不使用反射来提取它们。
此工具的页面拆分功能已从 PdfVeryDenseMergeTool
中提取自 this answer .此外,允许自定义分页符位置是抽象的。
public abstract class AbstractPdfPageSplittingTool {
public AbstractPdfPageSplittingTool(Rectangle size, float top) {
this.pageSize = size;
this.topMargin = top;
}
public void split(OutputStream outputStream, PdfReader... inputs) throws DocumentException, IOException {
try {
openDocument(outputStream);
for (PdfReader reader : inputs) {
split(reader);
}
} finally {
closeDocument();
}
}
void openDocument(OutputStream outputStream) throws DocumentException {
final Document document = new Document(pageSize, 36, 36, topMargin, 36);
final PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
this.document = document;
this.writer = writer;
newPage();
}
void closeDocument() {
try {
document.close();
} finally {
this.document = null;
this.writer = null;
this.yPosition = 0;
}
}
void newPage() {
document.newPage();
yPosition = pageSize.getTop(topMargin);
}
void split(PdfReader reader) throws IOException {
for (int page = 1; page <= reader.getNumberOfPages(); page++) {
split(reader, page);
}
}
void split(PdfReader reader, int page) throws IOException
{
PdfImportedPage importedPage = writer.getImportedPage(reader, page);
PdfContentByte directContent = writer.getDirectContent();
yPosition = pageSize.getTop();
Rectangle pageSizeToImport = reader.getPageSize(page);
float[] borderPositions = determineSplitPositions(reader, page);
if (borderPositions == null || borderPositions.length < 2)
return;
for (int borderIndex = 0; borderIndex + 1 < borderPositions.length; borderIndex++) {
float height = borderPositions[borderIndex] - borderPositions[borderIndex + 1];
if (height <= 0)
continue;
directContent.saveState();
directContent.rectangle(0, yPosition - height, pageSizeToImport.getWidth(), height);
directContent.clip();
directContent.newPath();
writer.getDirectContent().addTemplate(importedPage, 0, yPosition - (borderPositions[borderIndex] - pageSizeToImport.getBottom()));
directContent.restoreState();
newPage();
}
}
protected abstract float[] determineSplitPositions(PdfReader reader, int page);
Document document = null;
PdfWriter writer = null;
float yPosition = 0;
final Rectangle pageSize;
final float topMargin;
}
( AbstractPdfPageSplittingTool.java )
执行 OP 的任务:
I need to search my pdf for a specific string - Property Number:
Each time this is found, I need to add a page break ABOVE
可以像这样使用上面的类:
AbstractPdfPageSplittingTool tool = new AbstractPdfPageSplittingTool(PageSize.A4, 36) {
@Override
protected float[] determineSplitPositions(PdfReader reader, int page) {
Collection<TextRectangle> locations = Collections.emptyList();
try {
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
SearchTextLocationExtractionStrategy strategy = new SearchTextLocationExtractionStrategy(
Pattern.compile("Property Number"));
parser.processContent(page, strategy, Collections.emptyMap()).getResultantText();
locations = strategy.getLocations(null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<Float> borders = new ArrayList<>();
for (TextRectangle rectangle : locations)
{
borders.add((float)rectangle.getMaxY());
}
Rectangle pageSize = reader.getPageSize(page);
borders.add(pageSize.getTop());
borders.add(pageSize.getBottom());
Collections.sort(borders, Collections.reverseOrder());
float[] result = new float[borders.size()];
for (int i=0; i < result.length; i++)
result[i] = borders.get(i);
return result;
}
};
tool.split(new FileOutputStream(RESULT), new PdfReader(SOURCE));
( SplitPages.java 测试方法 testSplitDocumentAboveAngestellter
)
关于c# - 如何查找 PDF 中所有出现的特定文本并在上方插入分页符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45823741/
我的代码有一些问题。我正在尝试遍历包含许多 PDF 的 Drive 文件夹,然后将它们合并为一个文件。当我使用我的代码时,它只是为 Drive 文件夹中的最后一个 PDF 创建一个 PDF,而不是按预
我从 PDF Specification 获取了 PDF 规范中的最小 PDF 示例。 ,将其复制到记事本,将文件重命名为扩展名为 .pdf。 我可以用其他 PDF 查看器(PDF-XChange、S
感谢您在以下方面的帮助: 我有 2 个部分可访问的 PDF(包含标签),我想使用一些命令行工具(如 PDFtk 或 Ghostscript,或任何 Perl 模块)将它们连接起来: 我已经尝试使用 P
我想使用 ghostscript 将矢量 pdf 转换为光栅 pdf(即光栅化矢量 pdf)。但是即使我添加了解析参数 -r300,我也找不到合适的参数来执行此操作。 我使用的代码是-dSAFER -
我无法在 FAQ 中找到这个功能是否存在于 API 中,尽管它在书中提到作为潜在可用的东西。有没有人有任何实现此功能的经验? 最佳答案 在 This thread (日期为 2007 年 6 月)Pa
我要放文件sample.pdf在我的网站上,并希望使用 pdf.js 显示它.我想要的是显示我自己的文件,如 demo ,带有工具栏,放大/缩小等。到目前为止,我还不能这样做。 我确实检查了 hell
我知道这可能不是严格意义上的编程问题(也许是,我不知道)但我在尝试转换常规 pdf(带有超链接、书签、图像、嵌入字体等)时遇到了严重问题.) 转换为 PDF/A-1 格式。 当我用 pdfaPilot
这是 PDF.js 网站 https://github.com/mozilla/pdf.js 我正在搜索和阅读很多文章,大多数编码都是将 pdf 导入 pdf.js 并在浏览器上显示,我不明白是不是
谁能建议我如何将扫描图像转换为可搜索图像或如何将扫描 pdf 转换为可搜索 pdf? 很长一段时间以来,我一直陷入这种情况。 我已经在 ubuntu 中尝试过 pdfocr 应用程序,但没有成功。 最
作为我对客户端/服务器 pdf 签名研究的一部分,我测试了 itext pdf 延迟签名示例。不幸的是,我生成的 pdf 即合并空签名 pdf 和哈希值的输出显示无效签名。 我的代码片段如下 cla
我想将一个 PDF 页面插入到另一个已缩放的 PDF 页面中。我想使用 iTextSharp 来实现此目的。 我有一个矢量绘图,可以导出为单页 PDF 文件。我想将此文件添加到其他 PDF 文档的页面
作为我对客户端/服务器 pdf 签名研究的一部分,我测试了 itext pdf 延迟签名示例。不幸的是,我生成的 pdf 即合并空签名 pdf 和哈希值的输出显示无效签名。 我的代码片段如下 cla
我想为 Kindle 转换电子书。我尝试使用 Calibre 将具有复杂格式样式和图像的基于两种语言的基于文本的大型 PDF 电子书转换为适用于 Kindle 的 AZW3 电子书,并且还尝试了亚马逊
我在 Google Chrome 中显示 pdf 时遇到问题。问题是 Chrome 将 pdf 的某些页面显示为黑色。 启用 Chrome PDF 查看器时会发生这种情况。如果我禁用此插件并使用 Ad
我确信这个问题无处不在,尽管我似乎找不到答案。我希望我的 PDF 文档在 PDF 阅读器中显示时没有空白页,但随后在封面后打印空白页,这样打印出来的文档在右侧甚至左侧都有奇数页。还有其他人遇到过这个问
我需要自动裁剪 pdf 文件(去除白边)。到目前为止,我尝试了两种并不完美的工具: pdf裁剪 问题:它不会裁剪某些 pdf。 pdf-crop-margins 问题:有时它裁剪得太多(精细的细节)。
This PDF由几个源文件组成。其中五个是包含 alpha channel 的 PNG。一种是没有 alpha channel 的 PNG。最后一 block 是带有透明效果的 Photoshop
我的团队将内部 wiki 页面用于各种内容。这些页面是使用 MediaWiki 创建的。我想知道是否有任何方法可以将 wiki 页面转换为 PDF 格式。我必须用它来将用户文档转换为 PDF 格式,以
我希望能够从我可能在数据库或 xml 或任何其他结构化形式中拥有的数据生成高度图形化(也包含大量文本内容)的 PDF 文件。 目前,我们的平面设计师在将内容作为 MS Word 文档后,在 Photo
我正在寻找可以帮助我找到重复 PDF 的实用程序。问题:我有 1000 个 PDF 文件。有些是重复的。由于不同的文件名和文件大小的微小差异,它们不容易被检测到。是否有实用程序/算法/库可以帮助我找到
我是一名优秀的程序员,十分优秀!