Most answers to this question are five years old, PDF-only, and start by asking you to measure coordinates against a page you cannot see. Here is the 2026 version: seven calls, the two conventions that decide where the markup actually lands, and the single line a Linux container needs.
Everything below runs on .NET 8 and .NET 10, on Windows and Linux, with no Adobe Acrobat and no Microsoft Office installed — and the same code works on DOCX, XLSX, PPTX and images. Only the file path changes.
The runnable version is on GitHub: annotate-pdf-csharp-net.
설치
dotnet add package GroupDocs.Annotation
Without a licence the library runs in evaluation mode and the output carries evaluation marks. A temporary licence removes them:
new License().SetLicense("GroupDocs.Annotation.lic");
문서 열기
using (Annotator annotator = new Annotator("quarterly-review.pdf"))
{
// add, read or remove markup here
}
먼저 알아두어야 할 점: Annotator는 파일을 폐기될 때까지 열어 두며, 읽고 있는 파일에 바로 저장할 수 없습니다. 다른 경로에 저장하거나, 나중에 제자리로 이동시키는 임시 파일에 저장하십시오.
좌표를 측정하지 말고 텍스트를 검색하세요
대부분의 튜토리얼이 건너뛰는 부분이며, 문서의 다음 버전에서도 주석 코드를 유지하게 해주는 부분입니다. GetDocumentInfo()는 각 페이지의 크기와 텍스트 라인을 반환하며, 각 라인마다 박스가 있습니다:
IDocumentInfo info = annotator.Document.GetDocumentInfo();
foreach (PageInfo page in info.PagesInfo)
{
foreach (TextLineInfo line in page.TextLines)
{
if (line.Text.Contains("Hosting costs"))
{
// line.LeftIndent, line.TopIndent, line.Width, line.Height — points, from the top-left
}
}
}
이제 주석을 문서가 현재 말하고 있는 위치에 배치할 수 있으며, 작년의 위치에 배치하지 않아도 됩니다.
주석과 댓글, 답글이 포함된 하이라이트 추가
float left = (float)line.LeftIndent;
float right = (float)(line.LeftIndent + line.Width);
float top = (float)(page.Height - line.TopIndent);
float bottom = (float)(page.Height - line.TopIndent - line.Height);
annotator.Add(new HighlightAnnotation
{
PageNumber = page.PageNumber - 1,
BackgroundColor = 0xFFE699,
Opacity = 0.5,
Message = "Check this against the invoice",
CreatedOn = DateTime.Now,
User = new User { Id = 1, Name = "Reviewer", Role = Role.Editor },
Points = new List<Point>
{
new Point(left, top), new Point(right, top),
new Point(left, bottom), new Point(right, bottom)
},
Replies = new List<Reply>
{
new Reply { Comment = "Confirmed with finance.", RepliedOn = DateTime.Now }
}
});
annotator.Save("result.pdf");
Message는 댓글입니다. Replies는 스레드를 시작합니다 — PDF 리더에서는 응답이 달린 메모이며, Word에서는 아래에 답글이 달린 댓글입니다. User는 이후에 해당 검토자의 마크업을 정확히 찾아 제거하고 다른 사람들의 마크업은 그대로 두게 해줍니다.
모두에게 적용되는 두 가지 규칙
top과 bottom을 계산하는 두 줄, 그리고 PageNumber를 자세히 살펴보세요.
페이지 번호가 두 번 계산됩니다. PageInfo.PageNumber는 1부터 시작합니다. AnnotationBase.PageNumber는 0부터 시작합니다. 이를 혼용하면 모든 주석이 한 페이지씩 어긋나며, 마지막 페이지용 주석은 사라집니다. 존재하지 않는 페이지에 지정된 주석은 저장 시 예외나 경고 없이 삭제되기 때문입니다. 마크업이 “보이지 않는다”면, 다른 것을 확인하기 전에 페이지 인덱스를 확인하세요.
두 기준점. TextLineInfo와 AreaAnnotation.Box는 좌상단을 기준으로 측정됩니다. 텍스트 마크업 — 하이라이트, 밑줄, 취소선, 물결선 — 은 좌하단을 기준으로 측정되며, 이는 PDF 자체의 동작 방식입니다.
| 멤버 | 기준점 | 페이지 번호 |
|---|---|---|
PageInfo, TextLineInfo |
좌상단 | 1부터 시작 |
AnnotationBase.PageNumber |
— | 0부터 시작 |
AreaAnnotation.Box |
좌상단 | — |
HighlightAnnotation.Points |
좌하단 | — |
PreviewOptions.PageNumbers |
— | 1부터 시작 |
네 개의 점이 하나의 사각형을 만들며, 순서는 좌상단, 우상단, 좌하단, 우하단입니다. 동일한 리스트에 더 많은 사각형을 추가할 수 있는데, 이는 하나의 댓글이 세 줄에 걸쳐 있는 문장을 포괄하도록 합니다.
마크업 다시 읽기
using (Annotator annotator = new Annotator("result.pdf"))
{
foreach (AnnotationBase a in annotator.Get())
{
Console.WriteLine($"#{a.Id} {a.Type} on page {a.PageNumber + 1}: {a.Message}");
foreach (Reply reply in a.Replies)
Console.WriteLine($" reply: {reply.Comment}");
}
}
Get()은 문서에 실제로 포함된 내용을 읽어옵니다 — Word나 Acrobat에서 사용자가 추가한 주석도 포함되며, 이는 다른 도구를 거쳐도 정상적으로 동작하게 합니다.
알아두면 좋은 주의점: Id는 문서를 읽는 동안 할당되며 파일에 저장되지 않습니다. 같은 세션에서 주석을 삭제하거나 업데이트하기에 충분히 안정적이지만, 데이터베이스에 저장할 키는 아닙니다. 파일 외부에 주석을 보관하려면 가져오기와 내보내기를 사용하세요.
다시 제거하기
annotator.Remove(1); // by id
annotator.Remove(annotator.Get()
.Where(a => a.User?.Name == "Reviewer").ToList()); // or by author
페이지 렌더링
PreviewOptions previewOptions = new PreviewOptions(n => File.Create($"page_{n}.png"));
previewOptions.PreviewFormat = PreviewFormats.PNG;
previewOptions.PageNumbers = new[] { 1, 2 }; // 1-based
previewOptions.RenderAnnotations = true;
previewOptions.Resolution = 144;
annotator.Document.GeneratePreview(previewOptions);
세 가지 경우에 유용합니다: 문서를 표시하는 웹 UI, 마크업이 의도한 위치에 정확히 배치되었는지 확인하는 테스트, 그리고 자신의 작업을 검토해야 하는 에이전트.
Linux에서
코드는 변경되지 않습니다. 컨테이너만 변경됩니다:
FROM mcr.microsoft.com/dotnet/runtime:8.0
RUN apt-get update \
&& apt-get install -y --no-install-recommends fontconfig fonts-liberation \
&& rm -rf /var/lib/apt/lists/*
.NET 런타임 이미지에는 폰트가 포함되어 있지 않으며 텍스트 렌더링에 폰트가 필요합니다. 그 한 줄이 올바른 출력과 빈 페이지 사이의 차이를 만들며, 이는 일반적으로 문서 라이브러리와 관련된 가장 흔한 Linux 질문입니다.
다음 단계
git clone https://github.com/groupdocs-annotation/annotate-pdf-csharp-net.git
cd annotate-pdf-csharp-net
dotnet run --project src/AnnotatePdf -- highlight samples/quarterly-review.pdf --text "Hosting costs"
- Documentation: C#에서 PDF 주석 달기
- LLM이 계약을 검토하고 실제 댓글을 남기게 하기 — the same calls, driven by a model
- 브라우저 주석 UI 구축 — the same calls, driven by a person in a browser