PowerShell: Remove Line Breaks From Copied PDF Text

Advertisement
Remove line breaks from text copied out of a PDF with PowerShell File Operations
Advertisement

Paste a few paragraphs of a PDF into an email, and every line of the PDF turns into its own line. Fixing that by hand is tedious. The usual answer is a free "remove line breaks" website, but you can’t paste a confidential document into a random site, and a work laptop usually won’t let you install anything either.

I ran into this at work often enough that I wrote a small PowerShell window for it. You paste the text, click one button, and the cleaned-up text goes back to your clipboard. Nothing leaves your PC, and paragraph breaks and bullet points stay where they belong.

PowerShell window that removes line breaks from PDF text
Top: text as copied from the PDF. Bottom: the same text with the line breaks removed

Why PDF text comes out with a break on every line

A PDF stores text as lines placed at positions on the page. It keeps almost no record of paragraphs. When you copy, the viewer gives you one line of text per line on the page, so a break in the middle of a sentence looks exactly like a real paragraph break.

Here is how the common fixes compare.

Method How it works Downside
By hand Remove each break by hand Slow for anything longer than a few lines
Word Find and Replace Replace ^p (paragraph mark) with a space Every paragraph and bullet merges into one block
Online tools Paste into a website The text leaves your PC. Not an option for confidential documents
PowerShell (this post) Paste into a small window and click a button Paragraph detection is a guess, so the odd break may need a manual fix

It comes in handy any time PDF text has to go somewhere else. Typical cases are quoting a vendor’s PDF in a reply, moving part of a policy to a Word document, and sharing a passage in Teams or Slack.

What a plain paste looks like

For testing I made a two-page notice in PDF form, the kind an office sends around. Page 2 ends with an English summary of the notice, plus a page number at the bottom.

The two-page test notice used for this post
Page 2 has the English summary and a page number

I opened it in Adobe Acrobat, selected the English summary, copied it, and pasted it straight into Word with formatting marks turned on so every break is visible.

PDF text pasted into Word as is
Every line of the PDF ends in a paragraph mark, even mid-sentence

Each line of the PDF ends in a paragraph mark, even in the middle of a sentence (the new / system, cannot / attend). The page number came along as its own line too. Paste this into an email and the lines wrap at those spots.

The usual fix is Find and Replace in Word: replace ^p with a space. Here is the same text after that.

The same text after replacing every paragraph mark with a space
The heading runs into the paragraph, and the page number is stuck on the end

The breaks inside sentences are gone, but so is every break you wanted. The heading runs straight into the paragraph, and the page number is glued to the last sentence. With a longer document, bullets and paragraphs all collapse into one block, so you end up putting breaks back by hand. What you want is to remove only the breaks inside sentences, which is what the tool below does.

The script

First press Ctrl+C on the PDF text you need. Next, paste the whole script into a PowerShell window and press Enter. It runs in Windows PowerShell 5.1 as well as PowerShell 7. The window starts with your clipboard text in the top box. No admin rights needed.

# Remove line breaks from PDF text (PowerShell 5.1 / 7)
Add-Type -AssemblyName System.Windows.Forms, System.Drawing
[System.Windows.Forms.Application]::EnableVisualStyles()

# CJK characters (kana, kanji, full-width symbols)
$cjk = '[\u3000-\u30FF\u3400-\u9FFF\uF900-\uFAFF\uFF01-\uFF60]'
$reCjkEnd = $cjk + '$'
$reCjkStart = '^' + $cjk
$reLower = '^[a-z]'
$reHyphenEnd = '[A-Za-z]-$'

function Get-Width([string]$s) {                                 # line width: CJK counts as 2, everything else as 1
    $w = 0
    foreach ($ch in $s.ToCharArray()) { if ([string]$ch -match $cjk) { $w += 2 } else { $w += 1 } }
    return $w
}

function Join-PdfLines([string]$text) {
    $lines = $text -split "\r\n|\r|\n"
    $maxW = ($lines | ForEach-Object { Get-Width $_.Trim() } | Measure-Object -Maximum).Maximum
    $out = New-Object System.Collections.Generic.List[string]
    $buf = ""
    foreach ($raw in $lines) {
        $line = $raw.Trim()
        if ($line -eq "") {
            # blank line = paragraph break
            if ($buf) { $out.Add($buf); $buf = "" }
            if ($chkBlank.Checked -and $out.Count -gt 0 -and $out[$out.Count - 1] -ne "") { $out.Add("") }
            continue
        }
        if ($chkPage.Checked) {
            # page-number-only lines: 3, - 3 -, 3 / 10
            if ($line -match '^(-\s*)?\d{1,4}(\s*-)?$|^\d{1,4}\s*/\s*\d{1,4}$') { continue }
        }
        $newPara = $raw.StartsWith([string][char]0x3000)
        if ($chkBullet.Checked) {
            # bullet marks such as ・ ● • 1. 1) (1) ①
            if ($line -match '^([・●○■□◆◇※•▪]|\d{1,3}[..))](?!\d)|[((]\d{1,3}[))]|[①-⑳])') { $newPara = $true }
        }
        if ($newPara -and $buf) { $out.Add($buf); $buf = "" }
        $hyphenJoin = $chkHyphen.Checked -and ($buf -match $reHyphenEnd) -and ($line -cmatch $reLower)
        if ($buf -eq "") {
            $buf = $line
        } elseif ($hyphenJoin) {
            # infor- + mation
            $buf = $buf.TrimEnd("-") + $line
        } elseif (($buf -match $reCjkEnd) -or ($line -match $reCjkStart)) {
            # CJK text joins with no space
            $buf += $line
        } else {
            # words join with one space
            $buf += " " + $line
        }
        # Japanese sentence endings
        $endsSentence = $chkPeriod.Checked -and ($buf -match '[。!?」』]$')
        $shortLine = $chkShort.Checked -and ((Get-Width $line) -lt $maxW * 0.6)
        if ($endsSentence -or $shortLine) { $out.Add($buf); $buf = "" }
    }
    if ($buf) { $out.Add($buf) }
    while ($out.Count -gt 0 -and $out[$out.Count - 1] -eq "") { $out.RemoveAt($out.Count - 1) }
    return ($out -join "`r`n")
}

function Add-Ctl($ctl, $x, $y, $w, $h) {
    $ctl.Location = New-Object System.Drawing.Point($x, $y)
    $ctl.Size = New-Object System.Drawing.Size($w, $h)
    $form.Controls.Add($ctl)
    return $ctl
}
function New-Box {
    $box = New-Object System.Windows.Forms.TextBox
    $box.Multiline = $true; $box.ScrollBars = "Vertical"; $box.WordWrap = $true; $box.MaxLength = 0
    return $box
}

$form = New-Object System.Windows.Forms.Form
$form.Text = "Remove line breaks from PDF text"
$form.Size = New-Object System.Drawing.Size(820, 660)
$form.StartPosition = "CenterScreen"
$form.Font = New-Object System.Drawing.Font("Segoe UI", 9)

$lbl = Add-Ctl (New-Object System.Windows.Forms.Label) 12 10 780 20
$lbl.Text = "1. Text copied from a PDF (filled from the clipboard on start; you can also paste here)"
$txtIn = Add-Ctl (New-Box) 12 32 780 210

$chkBlank  = Add-Ctl (New-Object System.Windows.Forms.CheckBox) 12 250 380 22; $chkBlank.Text  = "Keep blank lines as paragraph breaks"
$chkPeriod = Add-Ctl (New-Object System.Windows.Forms.CheckBox) 400 250 390 22; $chkPeriod.Text = "Keep the break after a line ending in 。?」 (Japanese)"
$chkBullet = Add-Ctl (New-Object System.Windows.Forms.CheckBox) 12 274 380 22; $chkBullet.Text = "Keep the break before bullets (•, 1., (1), etc.)"
$chkPage   = Add-Ctl (New-Object System.Windows.Forms.CheckBox) 400 274 390 22; $chkPage.Text   = "Remove page-number lines (3, - 3 -, 3 / 10)"
$chkHyphen = Add-Ctl (New-Object System.Windows.Forms.CheckBox) 12 298 380 22; $chkHyphen.Text = "Rejoin words split by a hyphen (infor-mation)"
$chkShort  = Add-Ctl (New-Object System.Windows.Forms.CheckBox) 400 298 390 22; $chkShort.Text  = "Keep the break after short lines (headings, last lines)"
foreach ($c in @($chkBlank, $chkPeriod, $chkBullet, $chkPage, $chkHyphen, $chkShort)) { $c.Checked = $true }

$btnRun = Add-Ctl (New-Object System.Windows.Forms.Button) 12 328 260 34; $btnRun.Text = "2. Remove line breaks, copy result"
$btnClip = Add-Ctl (New-Object System.Windows.Forms.Button) 282 328 220 34; $btnClip.Text = "Reload from clipboard"
$lblInfo = Add-Ctl (New-Object System.Windows.Forms.Label) 512 337 280 20

$lbl = Add-Ctl (New-Object System.Windows.Forms.Label) 12 372 780 20; $lbl.Text = "3. Result (already on the clipboard, ready to paste)"
$txtOut = Add-Ctl (New-Box) 12 394 780 210

$loadClip = { $txtIn.Text = ((Get-Clipboard -Raw) -replace "(?<!\r)\n", "`r`n") }
$btnClip.Add_Click($loadClip)
$btnRun.Add_Click({
    if ($txtIn.Text.Trim() -eq "") { $lblInfo.Text = "Box 1 is empty"; return }
    $txtOut.Text = Join-PdfLines $txtIn.Text
    Set-Clipboard -Value $txtOut.Text
    $before = ($txtIn.Text -split "\r\n|\r|\n").Count
    $after = ($txtOut.Text -split "\r\n").Count
    $lblInfo.Text = "{0} lines -> {1} lines, copied" -f $before, $after
})

& $loadClip
[void]$form.ShowDialog()

Feel free to use and modify it.

Using it

Click “2. Remove line breaks, copy result”. The result appears in the bottom box, already copied to the clipboard, ready to paste. If you copy something else while the window is open, “Reload from clipboard” refreshes the top box.

All options start checked. Uncheck one to remove those breaks too.

Option What it does
Keep blank lines as paragraph breaks If the copied text has blank lines, they mark paragraphs
Keep the break after a line ending in 。?」 Japanese sentence endings. It does nothing for English text
Keep the break before bullets Lines starting with •, 1., (1) and similar stay on their own line
Remove page-number lines Drops lines that contain only 3, - 3 - or 3 / 10
Rejoin words split by a hyphen Turns "infor-" + "mation" back into "information"
Keep the break after short lines A line shorter than 60% of the longest line is treated as a heading or the last line of a paragraph

The script also handles Japanese, Chinese or Korean text: those lines are joined without a space. That is why the character ranges at the top are there.

Trying it on the same PDF

I pasted the same text into the tool and clicked the button. 8 lines became 2. Here is the result pasted into Word:

The tool result pasted into Word
The heading keeps its own line, the paragraph is one line, and the page number is gone

This is the text the tool put on the clipboard:

English summary
Starting next month, expense claims and attendance records will move to the new system. Please finish this month's requests by the end of the month. If you cannot attend a training session, the recording will be available on the internal portal for three months. For any questions, contact the General Affairs team. We appreciate your cooperation and clear communication with your team members during the transition.

The heading stays on its own line because it is short, the paragraph is one line with a single space in place of each break, and the page number is gone. I ran the same test in Windows PowerShell 5.1 and PowerShell 7 with identical results.

Things that tripped me up

There is no paragraph information to work with

Acrobat did not even keep the blank lines between paragraphs, so the script has to guess. It looks at four hints: short lines, bullets, indents, and sentence endings. A paragraph whose last line happens to be almost full width will run into the next one. When that happens, add the break by hand or try different options.

Acrobat removed the hyphen before the script saw it

In the PDF, “appreciate” is split across two lines as “appreci-” and “ate”. Acrobat rejoined it during the copy, so the hyphen option had nothing to do in this test. I kept the option for viewers that copy the hyphen as is.

Mixed-language text needs two joining rules

English needs a space in place of each break. Otherwise the last word on one line runs into the first word on the next. Japanese needs no space, otherwise you get gaps in the middle of sentences. The script checks the characters on both sides of each break and adds a space only between two non-CJK characters.

Related posts

Going the other way? Batch convert every Excel file in a folder to PDF also runs on a locked-down work PC. To list every file in a folder first, see exporting a file list to CSV for Excel.

Summary

  • PDFs barely record paragraphs, so copied text breaks at every line
  • A small PowerShell window removes those breaks without installing software or pasting text into a website
  • Paragraph breaks, bullets, even headings stay on their own lines

References

Comments

Copied title and URL